我在一个目录中有大约 4000 个 txt 文件。我想使用 for 循环将每个文件中的换行符替换为空格。实际上,该脚本为此目的工作,但是当我保存文件时,它不会被保存或再次使用换行符保存。这是我的脚本;
import glob
path = "path_to_files/*.txt"
for file in glob.glob(path):
with open(file, "r+") as f:
data = f.read().replace('n', ' ')
f.write(data)
正如我所说,我可以用空格替换换行符,但最后,它没有被保存。我也没有收到任何错误。
进一步阐述我的评论(">在'r+'模式下打开文件几乎总是一个坏主意(因为当前位置的处理方式(。打开文件进行读取,读取数据,替换换行符,打开相同的文件文件进行写入,写入数据"(:
for file in glob.glob(path):
with open(file) as f:
data = f.read().replace('n', ' ')
with open(file, "w") as f:
f.write(data)
您需要使用seek
将文件位置重置为 0,然后在完成写入替换字符串后用truncate
截断剩余部分。
import glob
path = "path_to_files/*.txt"
for file in glob.glob(path):
with open(file, "r+") as f:
data = f.read().replace('n', ' ')
f.seek(0)
f.write(data)
f.truncate()