【发布时间】:2015-10-24 10:34:16
【问题描述】:
我有一个包含很多行的文本文件。我需要在 Python 中的每一行附加一个文本。
这里是一个例子:
之前的文字:
car
house
blog
文字修改:
car: [word]
house: [word]
blog: [word]
【问题讨论】:
-
请分享您的尝试。
标签: python text formatting
我有一个包含很多行的文本文件。我需要在 Python 中的每一行附加一个文本。
这里是一个例子:
之前的文字:
car
house
blog
文字修改:
car: [word]
house: [word]
blog: [word]
【问题讨论】:
标签: python text formatting
如果您只想在每一行附加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)
【讨论】: