Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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 3.x 将列表写入文件并将其读回_Python 3.x - Fatal编程技术网

Python 3.x 将列表写入文件并将其读回

Python 3.x 将列表写入文件并将其读回,python-3.x,Python 3.x,我是一个初学者,我已经在这个论坛上搜索了我的答案,并尝试了以下例子(其中许多比我现在能理解的更复杂)。我想将我的列表变量写入一个文件,并在必要时将其读回 a = 'M' b = 456.78 c = 100 Variables = [a, b, c] f = open("test5.txt", "w") with open("test5.txt", "r") as opened_file: for variable in Variables: "test5.txt".w

我是一个初学者,我已经在这个论坛上搜索了我的答案,并尝试了以下例子(其中许多比我现在能理解的更复杂)。我想将我的列表变量写入一个文件,并在必要时将其读回

a = 'M'
b = 456.78
c = 100
Variables = [a, b, c]
f = open("test5.txt", "w")
with open("test5.txt", "r") as opened_file:
    for variable in Variables:
         "test5.txt".write(variable, '\n')
我得到一个“AttributeError”'str'对象没有属性'write'

  • 我该换什么
  • 我怎样才能把它读回来

  • 该错误意味着您无法写入字符串,而是要写入打开的文件。将字符串
    test5.txt
    更改为已打开的文件
    f

    for variable in Variables:
        f.write("%s\n" % variable)
    f.close()
    
    然后再读一遍:

    with open("test5.txt", "r") as opened_file:
        variables = opened_file.readlines()
    
    print(variables) #will print the file contents
    
    编辑:如评论中所述,原始请求无法将值重新分配给相应的变量名,下一个最佳选项是将从文件读取的每个值分配给原始列表中的索引。不幸的是,原始数据类型丢失,只保留字符串值

    for i in range(len(variables)):
        Variables[i] = variables[i].strip()
    
    print(Variables) # ['M', '456.78', '100']
    

    您能解释一下我的“…write(variable,'\n')与您的(“%s\n”%variable)有何不同吗?这只是另一种编码方式,还是我的错误?当然,写入文件时会将参数写入
    文件。write(str)
    只接受一个字符串参数,但
    (variable,'\n'))
    是两个参数,第一个是整数,第二个是字符串。
    %s\n”%variable
    是一个使用c样式格式的字符串。因此,您可以将变量转换为字符串,
    str(variable)
    ,然后用
    +
    运算符将它们连接成一个字符串。然后
    f.write(str(variable)+'\n''
    的工作原理也一样。我很抱歉纠缠。当我读回文件时,我确实这样做了,并且它完美地打印出了值,但是我如何将值重新分配给适当的变量名,以便我可以使用变量名(如b或c)进行计算?不用担心纠缠..!=)这是一个很好的问题,我正在尝试解决这个问题我在这个论坛上看到了如何做我想做的事情,他们基本上说“不要那样做”,而只是参考列表,就像在变量[2]中一样,如果我想要c的值-不是我想要的,但也可以按照他们说的方式做。谢谢