如何在替换后保留文件结构?
# -*- coding: cp1252 -*-
import os
import os.path
import sys
import fileinput
path = "C:\\Search_replace" # Insert the path to the directory of interest
#os.path.exists(path)
#raise SystemExit
Abspath = os.path.abspath(path)
print(Abspath)
dirList = os.listdir(path)
print ('seaching in', os.path.abspath(path))
for fname in dirList:
if fname.endswith('.txt') or fname.endswith('.srt'):
#print fname
full_path=Abspath + "\\" + fname
print full_path
for line in fileinput.FileInput(full_path, inplace=1):
line = line.replace("þ", "t")
line = line.replace("ª", "S")
line = line.replace("º", "s")
print line
print "done"
请您参考如下方法:
这个问题在清晰度方面不是很好,但是如果你想让 Python 将内容打印到标准输出而最后没有换行符,你可以使用 sys.stdout.write() 而不是 打印()。
如果您想执行替换并将其保存到文件中,您可以按照 Senthil Kumaran 的建议进行操作。
