2017-09-03 81 views
0

我想寫一個txt文件的多個東西,但由於某種原因,我不能讓每個條目結束了一個新的行。我在不同的地方放置了'\ n',但結果仍然相同。下面是正在使用的代碼:Python 3.X寫入文本文件不會創建新行

from collections import Counter 

File_1 = open('path1', 'r') 
wordCounter = Counter(File_1.read().lower().replace('<p>','').replace('<p><b>','').replace('</p>','').replace('</b>','').replace('.','').replace("'",'').replace('"','').replace('<i>','').replace('</i>','').replace(',','').replace('(','').replace('-','').replace(')','').replace('<b>','').replace(';','').split()) 
with open('path2','w') as File_2: 
    File_2.write('{:3} ==> {:15}'.format('Word','Count')) 
    File_2.write('-' * 18) 
    for (word,occurrence) in wordCounter.most_common(): 
     File_2.write('{:3} ==> {:15}'.format(word,occurrence)) 
File_1.close() 
File_2.close() 

試圖忽略了許多替代電話,我與需要清洗,纔可以進行排序一個靠不住的文本文件的工作。我想每個條目出現像這樣:

Word ==> Count 
Eighteen dashes 
Entry 1 ==> # of entries 
Entry 2 ==> # of entries 
etc. 

我到底是什麼了得到的是:

Word ==> Count ------------------Entry 1 ==> # of entriesEntry 2 ==> # of entries, etc. 

我覺得我可能在這裏做一個新手的錯誤,但有一個簡單的方法來將每個條目寫入新行的文件?預先感謝您的幫助。

+4

你做錯了。它是'\ n',而不是'/ n' –

回答

1

正如我所提到的,您使用的是backslah(\),而不是正斜槓(/)。

這是您的固定代碼:

from collections import Counter 
File_1 = open('path1', 'r') 
wordCounter = Counter(File_1.read().lower().replace('<p>','').replace('<p><b>','').replace('</p>','').replace('</b>','').replace('.','').replace("'",'').replace('"','').replace('<i>','').replace('</i>','').replace(',','').replace('(','').replace('-','').replace(')','').replace('<b>','').replace(';','').split()) 
with open('path2','w') as File_2: 
    File_2.write('{:3} ==> {:15}\n'.format('Word','Count')) 
    File_2.write(str('-' * 18)+'\n') 
    for (word,occurrence) in wordCounter.most_common(): 
     File_2.write('{:3} ==> {:15}\n'.format(word,occurrence)) 

File_1.close() 

你也不需要添加文件2密切,因爲有會替你

+0

這是解決方案,我把\ n放在錯誤的地方。非常感謝。 –

2

您可以使用print()函數重定向到一個文件。

此外,它使用with statement打開一個文件一個很好的做法:沒有必要擔心調用close()

from collections import Counter 


with open('path1', 'r') as file_1: 
    wordCounter = Counter(file_1.read().lower() 
          .replace('<p>','').replace('<p><b>','') 
          .replace('</p>','').replace('</b>','') 
          .replace('.','').replace("'",'') 
          .replace('"','').replace('<i>','') 
          .replace('</i>','').replace(',','') 
          .replace('(','').replace('-','') 
          .replace(')','').replace('<b>','') 
          .replace(';','').split()) 

with open('path2','w') as file_2: 
    print('{:3} ==> {:15}'.format('Word','Count'), file=file_2) 
    print('-' * 18, file=file_2) 
    for word, occurrence in wordCounter.most_common(): 
     print('{:3} ==> {:15}'.format(word,occurrence), file=file_2) 

我也建議你遵循PEP 8 — the Style Guide for Python Code,那就是你有命名約定解釋。

注:使用print()功能與Python 2,你可以在你的腳本的頂部使用__future__指令。

from __future__ import print_function 
+0

這並沒有回答他的問題。他希望添加換行 –

+0

感謝您提供的信息,我會研究風格指南並瞭解我可以改進的地方。 –

+0

@PokestarFan:'print()'函數添加換行符(除非你指定'end =「」')。 –