简体   繁体   中英

Python: Saving Loading Opening and Splitting text files

Problem I have a problem. I'm creating a file using w+ it creates a the text file that i need if it doesn't exist. Then save the file by using w . Opens file by using just plain open("file.txt") . can someone give it a quick fix please. what am i doing wrong here? thank you so much!

I get an error when loading the file for some reason it wont allow me to split it so that it becomes a variable.

Everything works when i remove the w+ from file = open("file.txt", "w+") in def player() . but if the textfile does not exist it wont create a new textfile and the program won't load.

def save():
    file = open("file.txt", "w")
    for i in myList:
    file.write(i) 
    file.write(" ")
    file.write(str(player)) 
    file.write(" ") 
    file.write(str(turn))
    print("Game Saved!") 
def load():
    # it can print the file text but does not print the variables theList, player, turn
    file = open("file.txt")
    for line in file:
    theList, player, turn = line.split(" ")


    print("Game Loaded!")

    if player == "1" and turn == "0" 
# example conditions, this is where i get error saying 
# local variable 'player' referenced before assignment

def superplayer():
    file = open("file.txt", "w+")
    for line in file:
        theList, player, turn = line.split(" ")
# and my code goes on

Do you ever close the file you open in each method? A good way to handle files is using with statement:

with open('file.txt', 'w+') as file:
    file.seek(0)
    #Do your file handling here
...

Have you checked the file for correct info since the player isn't assigned to?

Also try going to the start of the file before reading it with "w+":

file.seek(0)

You left a colon off on if player == "1" and turn == 0 . In addition, try to use the with keyword when using files, it's convention and makes things a lot easier for you.

In addition, make sure that player at least has a temporary value if the above doesn't fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM