2017-09-03 83 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 =“”')。 –