簡體   English   中英

向文本 output 文件添加換行符

[英]Adding line breaks to text output file

IDE output 顯示換行符,但 txt output 文件沒有。 我錯過了什么?

from bs4 import BeautifulSoup
import requests

source = requests.get('https://dota2.gamepedia.com/Category:Counters').text

soup = BeautifulSoup(source, 'lxml')
link = soup.find('div', class_="mw-category")

heroes_names = []

savefile = open('file.txt', 'w')

for link in link:
    link = link.text
    heroes = link.split("\n"
    for i in range(1,len(heroes)):
        heroname = heroes[i].split("/")[0]
        print(heroname)
        heroes_names.append(heroname)
        savefile.write(heroname)

# for hero_name in heroes_names:
#     print(hero_name)


savefile.close()

需要 output 到 txt 文件(不帶項目符號):

  • 阿巴頓
  • 煉金術士
  • 遠古幻影
  • 反法師
  • 天穹守望者
  • 斧頭
  • 禍根

實際 output 到 txt 文件: AbaddonAlchemistAncient ApparitionAnti-MageArc WardenAxeBane

首先,不要每次循環寫入文件。 在下面注釋的代碼中執行此操作也不要像您一樣打開文件

with open("file.txt", "a+") as f:
    for hero_name in heroes_names:
        print("Will write: %s" %hero_name)
        f.write("%s\n" %hero_name)

代替

savefile.write(heroname)

savefile.writeline(heroname + "\n")

這將在 output 的末尾添加一個換行符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM