我需要帮助以使脚本通过python包含两个进程: 在新文件夹中找到每个文本,然后将所有双精度空格都替换为1个制表符,然后再次执行将每个双精度空格都替换为1个制表符。
import fnmatch
import os
rootPath = "D:\A\B"
pattern = '*.txt'
for root, dirs, files in os.walk("D:\A\B"):
for filename in fnmatch.filter(files, pattern):
print(os.path.join(filename))
答案 0 :(得分:0)
glob
软件包可能比您所使用的更为简洁。然后只需打开文件,读入文本,替换要替换的内容,然后将其写回到同一文件即可。
在适当位置编辑文件时要小心-如果在错误的位置使用此文件,可能会造成严重损坏。
import os
import glob
root_path = r'D:\a\b' # use raw strings so \ is not escape character
patten = r'**\*.txt'
for path in glob.iglob(os.path.join(root_path, pattern), recursive=True):
# open the file to read and replace
with open(path) as fr:
text = fr.read().replace(' ', '\t').replace('\t\t', '\t')
# open the file to overwrite
with open(path, 'w') as fw:
path.write(text)