Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向文本输出文件添加换行符_Python - Fatal编程技术网

Python 向文本输出文件添加换行符

Python 向文本输出文件添加换行符,python,Python,IDE输出显示换行符,但txt输出文件不显示。我错过了什么 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

IDE输出显示换行符,但txt输出文件不显示。我错过了什么

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()
需要输出到txt文件(不带项目符号):

  • 末日
  • 炼金术士
  • 古代幽灵
  • 反法师
  • Arc管理员
  • 斧头
  • 祸根
实际输出到txt文件:
ABADDONAL古代幽灵反魔咒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)

首先,不要每次都在循环中写入文件。在下面的代码中执行此操作 也不要像你一样打开文件

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.write(heroname)

这将在输出的末尾添加换行符