替换后如何保留文件结构?
# -*- 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"
不要在fileinput行中使用
print line
,而是在末尾使用sys.stdout.write(line)
。不要在循环的其他地方使用打印。不用fileinput代替word replace,您还可以使用这个简单的方法代替word:
当您使用
如果这不是最后一行,
line
将包含行数据,包括换行符。所以通常在这种模式下,您要么想用或者打印出来而不附加自己的换行符(就像
print
那样)在clarity部门,这个问题不是很好,但是如果您希望Python打印出的东西在结尾没有换行符,那么您可以使用
sys.stdout.write()
,而不是print()
。如果要执行替换并将其保存到文件中,可以按照Senthil Kumaran的建议执行。
相关问题 更多 >
编程相关推荐