Skip to main content
 首页 » 编程设计

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

2025年05月04日14tuyile006

我有这个 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)(位置零 - 开头)。然后你就可以再写了。

希望这对您有所帮助。