2011-03-03 172 views
1

如何在替換後保留文件結構。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" 
+0

Joey:嗯... 。 什麼? – rossipedia 2011-03-03 06:45:48

回答

3

,而不是在的FileInput線print line,在最後做一個sys.stdout.write(line)。並且不要在循環中的其他地方使用打印標記。

而不是使用的FileInput一個字代替,也可以使用這種簡單的方法對單詞替換

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

逗號將只用空格替換換行符。 – 2011-03-03 06:49:17

+0

@Ignacio - 正確。編輯使用sys.stdout.write – 2011-03-03 06:56:08

+0

PS:[禁止換行的打印後面的逗號在Python 3中不起作用](http://www.ferg.org/projects/python_gotchas.html#table_of_contents_4)。 sys.stdout.write是最好的。 – smci 2011-07-03 23:23:52

3

的問題是在清晰度部門不是很大,但如果你想Python的打印的東西到標準輸出,而不在最後換行符可以使用sys.stdout.write()而不是print()

如果你想執行替換並將其保存到一個文件,你可以做什麼Senthil Kumaran建議。

0

當你遍歷文件的行與

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

line將包含行數據包括換行符這是不是最後一行。因此,在這種模式通常你要麼想要去除多餘的空白與

line = line.rstrip() 

或打印出來,而不附加自己的換行符(如print一樣)使用

sys.stdout.write(line)