2016-12-06 84 views
0

我有一個文本文件,它與各處的標籤格式化。下面是該文本文件看起來像現在:使用python腳本格式化文本文件

 "item1", 
     "item2", 
     "item3", 
     "item4", 
     "item5", 
     "item6", 
     "item7", 
     "item8", 
     .... 

事實上,該文本文件應該是這樣的:

"item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8", .... 

所以,我猜有多餘的標籤\t無處不在的原文件。

是否有可能以某種方式重新格式化這個列表(比方說)一個Python腳本?如何做到這一點?

回答

1

讀取文件,使用str.strip去掉行並同時寫入新文件。

帶將剝離從線要更換新行以及

with open('input.txt', 'r') as f, open('output.txt', 'w') as fo: 
    for line in f: 
     fo.write(line.strip()) 
     # fo.write(line.strip() + '\n') # use this if wanna retain new line 
1

如果該文件是不是大得離譜,看它作爲一個字符串,從字符串中刪除選項卡,並把它寫回:如果該文件是大

with open(file_name) as infile: 
    replaced = infile.read().replace("\t","") 
with open(another_file, "w") as outfile: 
    outfile.write(replaced) 

,閱讀並用一行行寫.readline().write()(假設它有換行符)。如果沒有換行符,則使用.read(N).write()一次讀寫N個字符。在這兩種情況下,在寫入之前用空字符串替換所有選項卡。

+0

做的左邊和右邊兩個選項卡或空格或換行的? –