gpt4 book ai didi

写入文件的 Python 函数不会在下次调用时切换到 else 语句

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:11 24 4
gpt4 key购买 nike

我有这个 python 函数,我正在尝试将增量 ID 保存到文件中。

def generate_id():
with open(".id.txt", "w+") as id:
person_id = id.read()
print('1:', person_id)
if person_id == '':
person_id = 1
id.write(str(person_id))
print("if", person_id)
return person_id
else:
person_id = int(person_id)
person_id += 1
id.truncate()
id.write(str(person_id))
print("else", person_id)
return person_id

问题是,这是我每次调用时得到的输出:

In [36]: generate_id()
1:
if 1
Out[36]: 1

In [37]: generate_id()
1:
if 1
Out[37]: 1

In [38]: generate_id()
1:
if 1
Out[38]: 1

关于如何让每次调用的值(value)增加的任何想法?


编辑

这是我用来解决我的问题的代码。感谢所有的帮助!

def generate_id():
with open(".id.txt", "a+") as unique_id: # a+ creates the file if it does not exist
unique_id.seek(0)
person_id = unique_id.read()

if not person_id:
person_id = 1
else:
person_id = int(person_id)
person_id += 1

with open(".id.txt", "w+") as unique_id:
unique_id.write(str(person_id))

return person_id

最佳答案

这似乎对我有用:

def generate_id():
with open("myfile.txt", "r+") as id:
person_id = id.read()
print('1:', person_id)
if person_id == '':
person_id = 1
id.write(str(person_id))
print("if", person_id)
return person_id
else:
person_id = int(person_id)
person_id += 1
id.seek(0)
id.truncate()
id.write(str(person_id))
print("else", person_id)
return person_id

w+ 替换为 r+w+ 甚至在您读取文件内容之前就删除了文件内容,因此文件将始终为空。另一方面,r+ 附加到文件。为了在写回之前删除内容,您需要将文件对象的指针设置为 0,这解释了 id.seek(0)(位置零 - 开头)。然后你就可以再写了。

希望这对您有所帮助。

关于写入文件的 Python 函数不会在下次调用时切换到 else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com