Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.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将其追加_Python - Fatal编程技术网

从文件中读取列表,并使用Python将其追加

从文件中读取列表,并使用Python将其追加,python,Python,我有一个名为usernames.py的文件,它可能包含一个列表,或者根本不存在: 用户名.py ['user1', 'user2', 'user3'] 在Python中,我现在想要读取这个文件(如果它存在),并将一个新用户附加到列表中,或者使用该用户创建一个列表,即。['user3'] 这就是我尝试过的: with open(path + 'usernames.py', 'w+') as file: file_string = host_file.read()

我有一个名为usernames.py的文件,它可能包含一个列表,或者根本不存在:

用户名.py

['user1', 'user2', 'user3']
在Python中,我现在想要读取这个文件(如果它存在),并将一个新用户附加到列表中,或者使用该用户创建一个列表,即。['user3']

这就是我尝试过的:

with open(path + 'usernames.py', 'w+') as file:
        file_string = host_file.read()
        file_string.append(instance)
        file.write(file_string)
这给了我一个未解决的错误“append”。我怎样才能做到这一点?Python不知道它是一个列表,如果文件不存在,即使是最糟糕的,因为我没有任何东西可以转换为列表。

尝试以下方法:

import os

filename = 'data'
if os.path.isfile(filename):
    with open(filename, 'r') as f:
        l = eval(f.readline())
else:
    l = []

l.append(instance)
with open(filename, 'w') as f:
    f.write(str(l))

但是,如果您不知道文件来自何处,那么这是非常不安全的,因为它可能包含执行任何操作的任何代码

最好不要使用python文件进行持久化——如果有人向您提供一个包含漏洞代码的usernames.py,会发生什么情况?考虑CSV文件或泡菜,或者只是一行一行的文本文件。

这就是说,如果您不将其作为python文件打开,类似这样的东西应该可以工作:

from os.path import join
with open( join(path, 'usernames.py'), 'r+') as file:
    file_string = file.read()
    file_string = file_string.strip().strip('[').strip(']')
    file_data = [ name.strip().strip('"').strip("'") for name in file_string.split(',' )]
    file_data.append( instance )
    file.fseek(0)
    file.write(str(file_data))

如果用户名包含逗号或以引号结尾,您必须更加小心。

是的,但由于它看起来像一个列表,Python不知道,或者我必须告诉Python它是一个列表吗?您应该使用
r+
模式。否则,文件在读取之前会被截断。@falsetru a+是否会工作,因为如果它不存在,我需要它来创建文件?@Spike,否。如果使用
a
模式打开文件,则无法更改文件位置(
file.seek
)。(至少在Linux中,总是在文件末尾写入happend。)a+仅在从
文件开始时才用于读取。seek(0)
(从开头开始)否则您已经是文件的结尾了。不确定为什么每个人都讨厌这个答案?不确定为什么Jamie也不喜欢。你好像读过我的作品,回答了我的问题谢谢。