开发者

Adding new line at the end of each line using Python

How can I preserve the file structure after substitution?

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


The question is not great in the clarity department, but if you want Python to print stuff to standard out without a newline at the end you can use sys.stdout.write() instead of print().

If you want to perform substitution and save it to a file, you can do what Senthil Kumaran suggested.


Instead of print line in the fileinput line, do a sys.stdout.write(line) at the end. And don't use print something in the other places in the loop.

Instead of using fileinput for word replace, you also use this simple method for word substitution:

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")


When you iterate the lines of the file with

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

the line will contain the line data including the linefeed character if this isn't the last line. So usually in this kind of pattern you will either want to strip the extra whitespace with

line = line.rstrip()

or print them out without appending your own linefeed (like print does) by using

sys.stdout.write(line)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜