[英]how to write whats print() to my console to a .txt file
我在python上很糟糕。 这段代码打印到控制台的正是我想要放入.txt文件的内容。 我尝试了几项失败。 由于我似乎无法附加正在使用的CSV文件,因此建议会有所帮助。
soccer_players.csv :
This is actually the entire CSV file:
Name,Height (inches),Soccer Experience,Guardian Name(s)
Joe Smith,42,YES,Jim and Jan Smith
Jill Tanner,36,YES,Clara Tanner
Bill Bon,43,YES,Sara and Jenny Bon
Eva Gordon,45,NO,Wendy and Mike Gordon
Matt Gill,40,NO,Charles and Sylvia Gill
Kimmy Stein,41,NO,Bill and Hillary Stein
Sammy Adams,45,NO,Jeff Adams
Karl Saygan,42,YES,Heather Bledsoe
Suzane Greenberg,44,YES,Henrietta Dumas
Sal Dali,41,NO,Gala Dali
Joe Kavalier,39,NO,Sam and Elaine Kavalier
Ben Finkelstein,44,NO,Aaron and Jill Finkelstein
Diego Soto,41,YES,Robin and Sarika Soto
Chloe Alaska,47,NO,David and Jamie Alaska
Arnold Willis,43,NO,Claire Willis
Phillip Helm,44,YES,Thomas Helm and Eva Jones
Les Clay,42,YES,Wynonna Brown
Herschel Krustofski,45,YES,Hyman and Rachel Krustofski
脚本 :
import csv
#open up the soccer_players.csv and turn the info into a big list with lists inside
if __name__ == "__main__":
with open('soccer_players.csv', newline='') as csvfile:
artreader = csv.reader(csvfile, delimiter=',')
rows = list(artreader)
header = rows.pop(0) #seperating the keys ex: "Name" from the values ex: "John"
for playerInfo in rows:
del playerInfo[1] #deleting the height from the lists as we don't need it.
experience = [] #a list of players with soccer experience
noExperience = [] #a list of players with no soccer experience
#putting the players into either the experience or noExperience lists
for row in rows:
if row[1] == "YES":
experience.append(row)
else:
noExperience.append(row)
teamSharks = []
teamDragons = []
teamRaptors = []
teams = [teamSharks, teamDragons, teamRaptors]
teamName = ["Sharks", "Dragons", "Raptors"]
#function combining 1/3 of the experienced/inexperienced into one of the three teams
def sortingIfPlayed(ifPlayed):
teamSharks.extend(ifPlayed[:int(len(ifPlayed)/3)])
teamDragons.extend(ifPlayed[int(len(ifPlayed)/3):int(len(ifPlayed)/(3/2))])
teamRaptors.extend(ifPlayed[int(len(ifPlayed)/(3/2)):])
sortingIfPlayed(experience)
sortingIfPlayed(noExperience)
#a function to take a list of players info by team, turn it into a string, and print it out
def printTeam(team):
for playerInfoList in team:
playerInfoString = ", ".join(playerInfoList)
print(playerInfoString)
print("")
x = 0
for team in teams:
print(teamName[x]) #prints the team's name above the list of players info
x += 1
printTeam(team) #calls the function to print the players info below the team name``
如何将whats print()写入控制台到.txt文件
您还可以通过更改sys.stdout
重定向stdout
,因为print
始终默认为打印到sys.stdout
。 只需在顶部添加以下行:
import sys
sys.stdout = open('yourtextfile.txt', 'w') # if yourtextfile.txt does not exist, it will create one, if it does, it will override it.
如果需要,您可以先保存原始的sys.stdout
以便在完成后可以将其更改回原样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.