Python 向文本输出文件添加换行符
IDE输出显示换行符,但txt输出文件不显示。我错过了什么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
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管理员
- 斧头
- 祸根
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)
做
这将在输出的末尾添加换行符