在Python中的每一行txt中追加文本

在Python中的每一行txt中追加文本,python,text,formatting,Python,Text,Formatting,我有一个有很多行的文本文件。我需要在每一行附加一个Python文本 这里有一个例子: 前面的文本: car house blog car: [word] house: [word] blog: [word] 文本修改: car house blog car: [word] house: [word] blog: [word] 阅读列表中的文本: f = open("filename.dat") lines = f.readlines() f.close() 附加文本: new_line

我有一个有很多行的文本文件。我需要在每一行附加一个Python文本

这里有一个例子:

前面的文本:

car
house
blog
car: [word]
house: [word]
blog: [word]
文本修改:

car
house
blog
car: [word]
house: [word]
blog: [word]

阅读列表中的文本:

f = open("filename.dat")
lines = f.readlines()
f.close()
附加文本:

new_lines = [x.strip() + "text_to_append" for x in lines]  
# removes newlines from the elements of the list, appends 
# the text for each element of the list in a list comprehension
编辑: 为了实现完整性,一个更具Python风格的解决方案是将文本写入新文件:

with open('filename.dat') as f:
    lines = f.readlines()
new_lines = [''.join([x.strip(), text_to_append, '\n']) for x in lines]
with open('filename_new.dat', 'w') as f:
    f.writelines(new_lines)

如果您只想在每一行添加
word
,这很好

file_name = 'YOUR_FILE_NAME.txt' #Put here your file

with open(file_name,'r') as fnr:
    text = fnr.readlines()

text = "".join([line.strip() + ': [word]\n' for line in text])

with open(file_name,'w') as fnw:
    fnw.write(text)

但是有很多方法可以做到这一点

请分享你的尝试。with绝对比只打开和关闭要好。OTOH修改原始文件从来都不是一个好主意-如果你搞砸了,你就很难重新开始