简体   繁体   English

Python 3.X写入txt文件不会创建新行

[英]Python 3.X Writing to txt File will not create new lines

I am trying to write multiple things to a txt file, but for some reason I cannot get each entry to end up on a new line. 我试图将多个内容写入txt文件,但是由于某些原因,我无法使每个条目都以新行结尾。 I have messed with placing '\\n' in different spots, but the result is still the same. 我已经把'\\ n'放在不同的位置弄得一团糟,但是结果还是一样。 Below is the code being used: 下面是使用的代码:

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

Try to ignore the many replace calls, I am working with a wonky text file that needs cleaning before it can be sorted. 尝试忽略许多替换调用,我正在处理一个需要清除才能分类的文本文件。 I want each entry to appear like so: 我希望每个条目都像这样显示:

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

What I end up getting is: 我最终得到的是:

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

I feel like I am probably making a rookie mistake here, but is there an easy way to get the file to write each entry onto a new line? 我觉得我可能在这里犯了一个菜鸟错误,但是是否有一种简单的方法来获取将每个条目写入新行的文件? Thanks in advance for any assistance. 在此先感谢您的协助。

You can use the print() function with a redirection to a file. 您可以将print()函数与重定向到文件一起使用。

Also, it's a good practice to use a with statement to open a file: no need to worry about the call to close() : 另外,使用with语句打开文件也是一种好习惯:无需担心调用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)

I also recommend you to follow the PEP 8 — the Style Guide for Python Code , where you have naming conventions explained. 我还建议您遵循PEP 8 — Python代码样式指南 ,在其中解释了命名约定。

note: to use the print() function with Python 2, you can use the __future__ directive at the top of your script. 注意:要在Python 2中使用print()函数,可以在脚本顶部使用__future__指令。

from __future__ import print_function

As I mentioned, you use backslah ( \\ ), not forward slash ( / ). 如前所述,您使用的是backslah( \\ ),而不是正斜杠( / )。

This is your fixed code: 这是您的固定代码:

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

You also do not need to add a close for File2, since with does that for you 您也不需要为File2添加关闭,因为这样做可以为您完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM