Home > Net >  Python List does include the most recent stuff added to the file
Python List does include the most recent stuff added to the file

Time:01-10

I've been trying to add a save function to a game by having the user enter their initials which gets saved to a file with their score so then it can load were they were before. At the start it asks for their initials and saves it to a file, then I want to the file to be copied onto a list so the score can be edited, however the list doesn't include the most recent initials and score added the file. I don't know where the problem is so I've added the file stuff I did.

  Names.write('~~~') 
  Names.write('\n')
  Names.write(username_score)
  Names.write('\n')
  line = Names.readlines()
  print(line)
with open('Names.txt','r ') as Names:
  for line_number, data in enumerate(Names, start=1):
    if username in data:
      print(f"Word '{username}' found on line {line_number}")
      break
  print('data',data)
  print('line',line)
  line.pop(1)
  line.insert(1, username_score)
  print('line 2',line)

  for i in range(len(line)):
    Names.write(line[i])

CodePudding user response:

I think this is because in your first code block, you are trying to write and then read the file without closing and reopening the file. The line = Names.readlines() line should be in the second code block like so:

username_score = '200'
username = 'foo'

with open('Names.txt','w ') as Names:
    Names.write('~~~')
    Names.write('\n')
    Names.write(username_score)
    Names.write('\n')
    line = Names.readlines()
    print(line)

with open('Names.txt','r ') as Names:
  line = Names.readlines()
  print(line)
  for line_number, data in enumerate(line, start=0):
    if username in data:
      print(f"Word '{username}' found on line {line_number}")
      break
  print('data',data)
  print('line',line)
  line.pop(1)
  line.insert(1, username_score)
  print('line 2',line)

  for i in range(len(line)):
    Names.write(line[i])

This full example should be easy enough to integrate into your code, and if you have any questions leave a comment.

  •  Tags:  
  • Related