【问题标题】:How to add a word at end of a text file? [duplicate]如何在文本文件末尾添加一个单词? [复制]
【发布时间】:2021-09-01 07:03:10
【问题描述】:

我在一个文件夹中有 500 个文本文件,每个文件如下所示:

1-1,2-4,In,_,
1-2,5-9,this,_,
1-3,10-15,paper,_,
1-4,16-18,we,_,
1-5,19-26,propose,_,
1-6,27-28,a,Project[1],

我需要在每个文件的文本末尾添加一个单词。我期望的结果是:

1-1,2-4,In,_,
1-2,5-9,this,_,
1-3,10-15,paper,_,
1-4,16-18,we,_,
1-5,19-26,propose,_,
1-6,27-28,a,Project[1],
end

如何在with 块内写入内容?

import os

path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
    with open(os.path.join(path, file), 'r',encoding='utf-8') as f:
        ### add "end" to end of the file

还是我应该使用 pandas 数据框来完成它们?

【问题讨论】:

标签: python pandas


【解决方案1】:

假设你的文件名为"foo.txt",你可以像这样追加打开它:

with open("foo.txt", "a") as f:
    f.write("\nend")

\n 表示插入 end 之前的换行符。

【讨论】:

    【解决方案2】:

    这个答案应该会有所帮助: Write to the last line of a text file?

    只需以追加模式打开文件(指针将在文件的 ned 中)并写入行。

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2023-04-08
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      相关资源
      最近更新 更多