我开发了一个脚本,删除文件末尾的所有空格。
import sys
with open("/Users/XXXXX/Desktop/XXXXX.txt") as infile:
lines = infile.read()
while lines.endswith("\n"):
lines = lines[:-2]
with open("/Users/XXXXX/Desktop/XXXXX.txt", 'w') as outfile:
for line in lines:
outfile.write(line)
脚本工作正常但我在一个文件夹中有两千个小文件,我需要删除所有空格。
有人可以指导我如何更改我的脚本,这样我就可以打开文件夹中的每个文件并运行上面的脚本了吗?
感谢,
答案 0 :(得分:1)
请尝试以下代码:
import os
import sys
def removeNewLines(file):
with open(file , 'r') as infile:
lines = infile.read()
while lines.endswith("\n"):
lines = lines[:-2]
with open(file, 'w') as outfile:
for line in lines:
outfile.write(line)
all_files = os.listdir('FOLDER PATH')
for file in all_files:
removeNewLines(file)