简体   繁体   English

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

[英]Append text in every line of txt in Python

I've a text file with many lines. 我有一个包含多行的文本文件。 I need to append to every line a text in Python. 我需要在Python的每一行后面附加一个文本。

Here an example: 这里是一个例子:

Text before: 之前的文字:

car
house
blog

Text modified: 文字已修改:

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

If you just want to append word on each line this works fine 如果您只想在每行上附加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)

But there are many ways to do it 但是有很多方法可以做到

Read the text in a list: 阅读列表中的文本:

f = open("filename.dat")
lines = f.readlines()
f.close()

append text: 附加文字:

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

Edit: for completness, a more pythonic solution with writing the text to a new file: 编辑:为了完整起见,将文本写入新文件的更多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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM