我在这里遇到了一些麻烦。我有一个带有["Data1", "Data2", "Data3"]
的文本文件,如果 data1
不在文件中,我想要,然后添加一个包含所有三个字符串的新列表,如果是数据已经存在,然后打印它。这段代码中有什么问题?为什么?
filename = "datosdeusuario.txt"
leyendo = open(filename, 'r')
if user.name in leyendo:
Print("Your user name is already there")
else:
file = open(filename, 'a')
file.write(json.dumps([user.name, "data2", "data3"])+"\n")
file.close()
Print("Since I couldn't find it, I did append your name and data.")
P.S。:我是Python的新手,我经常感到困惑。这就是为什么我没有使用任何dicts(不知道它们是什么),所以我想以最简单的方式使代码工作。
P.S.2:另外,如果可行,我的下一步是让搜索引擎返回列表中三个数据项中的一个特定项。例如,如果我想在用户名为“sael”的列表中获取data2,我还需要做什么?
答案 0 :(得分:1)
假设您的user.name和Print
函数正在运行,您需要读取该文件并关闭该文件。
试试这个:
filename = "datosdeusuario.txt"
f = open(filename, 'r')
leyendo = f.read()
f.close()
if user.name in leyendo:
Print("Your user name is already there")
else:
file = open(filename, 'a')
file.write(json.dumps([user.name, "data2", "data3"])+"\n")
file.close()
Print("Since I couldn't find it, I did append your name and data.")
答案 1 :(得分:1)
首先,您应该在两种情况下关闭文件,我认为您应该在重新打开文件之前关闭该文件以进行追加。
我认为问题在于:
if user.name in leyendo:
总是返回false。
您应该阅读该文件,然后对其进行质询:
if user.name in leyendo.read():
答案 2 :(得分:1)
您似乎正在读取文件指针,而不是按照预期从文件中的数据读取。
因此,您首先需要读取文件中的数据:
buffer = leyendo.read()
然后根据buffer
进行检查,而不是leyendo
:
if user.name in buffer:
另外,你打开文件两次,这可能有点贵。我不确定Python是否具有在读写模式下打开文件的功能。