Python没有将整个输出写入文件

2024-09-19 23:58:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将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>

Tags: 文件orgtxtidwwwwithopencn
3条回答

将新字符串分配给组合变量时,必须将旧字符串与已分配的组合变量相加,才能分配所有字符串

internallink = "www.icom.org.cn"
combined = ''
for every_line in tt:
    # If you don't want the text on newline you can remove `\n`
    combined = combined + internallink + every_line.strip() + '\n' 

print(combined)

输出:-

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

也许您需要一种嵌套的方法:

with open(r"C:\Users\xingj\Desktop\writing.txt") as f, open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    for line in f:
        b.write('www.icom.org.cn'+line)

在while循环中,将out_str变量重新分配给当前值combined。相反,对于所需的输出,您应该将新值追加到combinedout_str。 替换

for every_line in f:
    combined = (internallink + every_line.strip())
    out_str = "".join(combined)

for every_line in f:
    combined = (internallink + every_line.strip())
    out_str = out_str + combined

你的代码应该很好

相关问题 更多 >