使用Python在每行末尾添加新行

2024-06-17 15:40:02 发布

您现在位置:Python中文网/ 问答频道 /正文

替换后如何保留文件结构?

# -*- 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"

Tags: thepathinimportforoslinefname
3条回答

不要在fileinput行中使用print line,而是在末尾使用sys.stdout.write(line)。不要在循环的其他地方使用打印。

不用fileinput代替word replace,您还可以使用这个简单的方法代替word:

import shutil
o = open("outputfile","w") #open an outputfile for writing
with open("inputfile") as infile:
   for line in infile:
     line = line.replace("someword","newword")
     o.write(line + "\n")
o.close()
shutil.move("outputfile","inputfile")

当您使用

 for line in fileinput.FileInput(full_path,inplace=1)

如果这不是最后一行,line将包含行数据,包括换行符。所以通常在这种模式下,您要么想用

line = line.rstrip()

或者打印出来而不附加自己的换行符(就像print那样)

sys.stdout.write(line)

在clarity部门,这个问题不是很好,但是如果您希望Python打印出的东西在结尾没有换行符,那么您可以使用sys.stdout.write(),而不是print()

如果要执行替换并将其保存到文件中,可以按照Senthil Kumaran的建议执行。

相关问题 更多 >