首页 > 解决方案 > 如何在文本文件末尾添加一个单词?

问题描述

我在一个文件夹中有 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

还是我应该使用熊猫数据框来做它们?

标签: pythonpandas

解决方案


假设您的文件被称为"foo.txt",您可以打开它并打算像这样附加它:

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

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


推荐阅读