Python not creating file -


i'm trying write text file in python. file doesn't yet exist i'm using:

def writetotextfile(players):     file = open('rankings.txt', 'a')     player in players:         file.write(player.name, player.rating, player.school, '\n')     file.close() 

i used 'a' append , thought create new file (based on documentation). on desktop (where i'm running script from) , there's no "rankings.txt" file found.

any thoughts on how fix?

thanks, bclayman

the syntax write command incorrect. function accepts string argument. example:

file.write("{}, {}, {}\n".format(player.name, player.rating, player.school)) 

i've mocked quick example of full script show in action:

class player(object):     def __init__(self, name, rating, school):         self.name = name         self.rating = rating         self.school = school  def writetotextfile(players):     f = open('rankings.txt', 'a')     player in players:         f.write("{}, {}, {}\n".format(player.name, player.rating, player.school))     f.close()   players = [] x in range(5):     name = 'name {}'.format(x)     rating = 100 - x     school = 'school {}'.format(x)     players.append(player(name, rating, school))  writetotextfile(players) 

this script creates 5 player objects , appends them players list. passed writetotextfile function. creates rankings.txt file in location running script following output:

name 0, 100, school 0 name 1, 99, school 1 name 2, 98, school 2 name 3, 97, school 3 name 4, 96, school 4 

changes or improvements make:

  • i changed file variable f prevent shadowing built in object same name.
  • another change can make using with instead of manually opening , closeing file objects.

this can done so:

with open('rankings.txt', 'a') f:     player in players:         f.write("{}, {}, {}\n".format(player.name, player.rating, player.school)) 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -