我正在尝试将txt文件中的每一行与标题文本连接起来。但成功加入后,
排队。我似乎无法正确地写入文件,因为它只会将最后一个连接行写入internallinks.txt
。如何将combined
的整个输出写入文件
任何帮助都将不胜感激,非常感谢
Python代码
with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
internallink = ("www.icom.org.cn")
for every_line in f:
combined = (internallink + every_line.strip())
out_str = "".join(combined)
with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
b.write(out_str)
writing.txt的内容
/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&
internallinks.txt的输出
www.icom.org.cn/icom/faculty/viewer/?id=470&
关闭with
之前的print (combined)
命令的输出
PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>
将新字符串分配给组合变量时,必须将旧字符串与已分配的组合变量相加,才能分配所有字符串
输出:-
也许您需要一种嵌套的方法:
在while循环中,将
out_str
变量重新分配给当前值combined
。相反,对于所需的输出,您应该将新值追加到combined
到out_str
。 替换与
你的代码应该很好
相关问题 更多 >
编程相关推荐