【问题标题】:Append text in every line of txt in Python在 Python 中的每一行 txt 中附加文本
【发布时间】:2015-10-24 10:34:16
【问题描述】:

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

这里是一个例子:

之前的文字:

car
house
blog

文字修改:

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

【问题讨论】:

  • 请分享您的尝试。

标签: python text formatting


【解决方案1】:

如果您只想在每一行附加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,修改原始文件绝不是一个好主意 - 如果你搞砸了,你就很难重新开始
【解决方案2】:

阅读列表中的文本:

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)

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 2021-10-17
    • 2012-03-21
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多