简体   繁体   English

Python:保存正在加载的打开和拆分文本文件

[英]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. 我正在使用w+创建文件,如果文件不存在,它将创建我需要的文本文件。 Then save the file by using w . 然后使用w保存文件。 Opens file by using just plain open("file.txt") . 通过仅使用纯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() . 当我from file = open("file.txt", "w+") def player() from file = open("file.txt", "w+")中删除w+时,一切正常。 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语句:

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+": 还可以尝试使用“ w +”读取文件之前,先转到文件的开头:

file.seek(0)

You left a colon off on if player == "1" and turn == 0 . 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. 另外,在使用文件时,请尝试使用with关键字,这是惯例,这会使您的工作变得容易得多。

In addition, make sure that player at least has a temporary value if the above doesn't fix your problem. 此外,如果上述方法不能解决您的问题,请确保player至少具有一个临时值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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