如何制作脚本以将双 space 替换为制表符?
How to make script to replace double space to tab?
我需要 python 的帮助来使脚本包含两个进程:
在新文件夹中找到每个文本并将所有双 space 替换为 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))
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)
我需要 python 的帮助来使脚本包含两个进程: 在新文件夹中找到每个文本并将所有双 space 替换为 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))
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)