当前位置: 代码迷 >> python >> 在Python中的txt每一行中附加文本
  详细解决方案

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

热度:95   发布时间:2023-06-13 20:26:05.0

我有一个包含多行的文本文件。 我需要在Python的每一行后面附加一个文本。

这里是一个例子:

之前的文字:

car
house
blog

文字已修改:

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

如果您只想在每行上附加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)

但是有很多方法可以做到

阅读列表中的文本:

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

编辑:为了完整起见,将文本写入新文件的更多pythonic解决方案:

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)