在程序的多次运行之间递增变量值的问题

Problem with incrementing the value of a variable between several runs of the program

见以下代码:

def increment():
    x = 0
    file = open(f'file{x}.txt', 'a')
    file.write("something...")
    file.close()
    x = x + 1

你可能已经明白我在这里想做什么了。但问题是,每次我 运行 程序 x 的值设置为 0 并且每次打开文件时, file1.txt,我什至尝试过此代码:

x = 0
def increment():
    file = open(f'file{x}.txt', 'a')
    file.write("something...")
    file.close()
    x = x + 1

在函数外赋值,还是一样的问题。我希望它打开这样的文件:
首先运行:file1.txt,
第二个运行:file2.txt,
第三个运行:file3.txt等等...
但它总是打开文件,file1.txt.

变量存储在内存中,而不是硬盘中。每当您的程序结束并且进程终止时,Python 将自动删除对内存中创建的对象的所有引用,因此所有对象都将消失...

为此,您有 2 个选择:

解决方案 1:

您需要以某种方式将该号码存储在硬盘中。可能位于单独的文本文件中。然后,每当您想创建新文件时,首先读取该文件并从中获取该编号。做好你的工作,最后别忘了回信。

喜欢:

# getting the number (assumed this file is already present
# and has the first line filled with a number)
with open("read_number.txt") as f:
    x = int(f.read())

with open(f"file{x}.txt", 'a') as f:
    f.write("something\n")

with open("read_number.txt", 'w') as f:
    x += 1
    f.write(str(x))

解决方案 2:

另一种解决方案是每当您想创建一个新文件时,搜索目录,获取所有名称(os.listdir)并对其进行排序。然后你可以得到姓氏,并且可以轻松地将它加一。

类似于:

import os
import re

lst = [i for i in os.listdir() if i.startswith("file")]
lst.sort(key=lambda x: int(re.search(r'\d+', x).group()))
print(lst)

你可以通过多种方式做到这一点,我只是想告诉你路径。

如果你想在这里完成的是用递增的数字保存文件,那么一种方法可以是从 x = 0 开始,每次程序是 运行 然后检查是否有名称为 file{x} 的文件存在,如果存在则递增并再次检查,如果不存在则简单地使用该文件名。

像这样-:

from os import path

def increment() :
    x = 0
    while path.exists('file' + str(x)) :
        continue
    file_name = 'file' + str(x)
    with open(file_name) as f :
        #....
        pass
    return

这里判断一个文件是否存在,可以使用os.path模块的exists方法