Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python .txt读取以更改全局变量_Python_Python 3.x - Fatal编程技术网

Python .txt读取以更改全局变量

Python .txt读取以更改全局变量,python,python-3.x,Python,Python 3.x,所以我让一个玩家输入他/她的名字。该名称将写入一个文件。然后打开、读取文件,并将全局变量更改为所述文件中的变量。这最终将成为我为一个类开发的游戏的保存功能 def nameWrite(): text_file = open("name.txt", "w+") print('what u name') text_file.write(input()) text_file.close() def nameRead(): text_file = open("n

所以我让一个玩家输入他/她的名字。该名称将写入一个文件。然后打开、读取文件,并将全局变量更改为所述文件中的变量。这最终将成为我为一个类开发的游戏的保存功能

def nameWrite():
    text_file = open("name.txt", "w+")
    print('what u name')
    text_file.write(input())
    text_file.close()

def nameRead():
    text_file = open("name.txt","r")
    print ("This is the output in file:",text_file.read())
    global playerName
    playerName = text_file.read()
    text_file.close()

nameWrite()
nameRead()
print("You name is now:",playerName)
为什么这不会更改变量
playerName

全局变量正在更新,只是没有更新到您认为应该更新的位置

请看下面的代码:

def nameRead():
    text_file = open("name.txt","r")                         # 1
    print ("This is the output in file:",text_file.read())   # 2
    global playerName
    playerName = text_file.read()                            # 3
    text_file.close()
当它执行时,会发生以下情况:

  • 文件已打开
  • 读取文件中的所有数据,并将文件指针移到文件末尾
  • 下次读取时,没有更多的数据要读取,因此playerName是空字符串

  • 除非关闭并重新打开文件,或者使用
    seek
    函数将文件指针移回开头,否则无法读取文件两次

    全局变量没有更新代码看起来可以工作,有什么问题吗?我真的不喜欢使用
    global
    ;最好只让您的
    nameRead()
    函数
    returnplayername
    。当您调用
    .read()
    时,将读取文件内容。第二次调用
    .read()。一种可能的解决方案是在打印内容之前将文件内容分配给变量。@bernie感谢上帝,我觉得dumb@JohnBrook字体请不要那样想。这种感觉只会破坏你的工作效率。我们都曾有过这样的经历。去找下一个虫子!