[英]Splitting text file to separate files, and saving substrings in filenames; Python
[英]Python: Saving Loading Opening and Splitting text files
問題我有問題。 我正在使用w+
創建文件,如果文件不存在,它將創建我需要的文本文件。 然后使用w
保存文件。 通過僅使用純open("file.txt")
打開文件。 有人可以快速解決嗎。 我在這里做錯了什么? 非常感謝!
由於某種原因,在加載文件時出現錯誤,它不允許我拆分它,使其成為變量。
當我from file = open("file.txt", "w+")
def player()
from file = open("file.txt", "w+")
中刪除w+
時,一切正常。 但是,如果文本文件不存在,它將不會創建新的文本文件,也不會加載程序。
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
您是否曾經關閉過每種方法中打開的文件? 處理文件的一種好方法是使用with語句:
with open('file.txt', 'w+') as file:
file.seek(0)
#Do your file handling here
...
由於未分配播放器,您是否檢查了文件中的正確信息?
還可以嘗試使用“ w +”讀取文件之前,先轉到文件的開頭:
file.seek(0)
if player == "1" and turn == 0
您就不用冒號了。 另外,在使用文件時,請嘗試使用with
關鍵字,這是慣例,這會使您的工作變得容易得多。
此外,如果上述方法不能解決您的問題,請確保player
至少具有一個臨時值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.