Python:如何扫描文件,如果找不到,那么添加一个新文件?

时间:2017-08-25 03:20:14

标签: python file while-loop

我正在尝试创建一个程序,每次运行时都会写一个新文件。

例如:

我运行程序一次。该文件夹为空,因此它将文件添加到名为" Test_Number_1.txt"

的文件夹中

我第二次运行该程序。该文件夹有一个文件,因此它将其扫描为文件,扫描另一个文件但没有文件,因此它创建一个名为" Test_Number_2.txt"

的新文件

这就是我的想法,但代码不会离开while循环。我还是编程的新手,所以请原谅我的低效编码哈哈。

memory = # something that changes each time I run the program
print(memory)
print("<-<<----<<<---------<+>--------->>>---->>->")
found_new = False
which_file = 0

while not found_new:
    try:
        file = open("path_to_folder/Test_Number_" + str(which_file) + ".txt", "a")
    except FileNotFoundError:
        which_file += 1
        file_w = open("path_to_folder/Test_Number_" + str(which_file) + ".txt", "w")
        found_new = True
        break
    print("Looked", which_file, "times.")
    which_file += 1
    time.sleep(1)
file = open("path_to_folder/Test_Number_" + str(which_file) + ".txt", "a")
file.write(memory)
file.close()
print("Done.")

我把time.sleep(1)延迟进程以防出现错误,这样我的整个计算机都不会过载并感谢良好,因为程序只是不断添加越来越多的文件,直到我强制退出它

1 个答案:

答案 0 :(得分:2)

一个简单的解决方案

from os.path import isfile

def file_n(n):
  return "Test_number_" + str(n) + ".txt"

n = 0
while isfile(file_n(n)):
  n += 1
f = open( file_n(n), "w" )
f.write("data...")
f.close()

问题在于,如果同一程序的许多实例同时运行,则可能会覆盖某些文件。