python - 如何在文本文件末尾添加一个单词?
问题描述
我在一个文件夹中有 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
还是我应该使用熊猫数据框来做它们?
解决方案
假设您的文件被称为"foo.txt"
,您可以打开它并打算像这样附加它:
with open("foo.txt", "a") as f:
f.write("\nend")
\n
表示插入之前的换行符end
。
推荐阅读
- python - 使用 Trello API (python) 在列表之间移动卡片
- pool - 查询 Pancakeswap Auto CAKE 池的用户质押奖励信息的合约是什么?
- javascript - 网络服务器上的 Docxtemplater CORS 策略
- gradle - Gradle 一次只解决两个依赖项中的一个
- javascript - 如何在嵌套数组中删除数组
- r - R - 指示每组是否某个列是统一的或包含不同的因子值
- javascript - OpenLayers 6.8:如何获取 Geojson 矢量坐标?
- php - Eloquent 关系仅返回数组中第一个结果的结果
- php - 在 Wordpress 中创建时在 Strapi 中创建用户
- recurrent-neural-network - 层 lstm_6 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:(无,20000)