2017-08-25 36 views
0

我正在试图制作一个程序,每次运行时都会写入一个新文件。Python:我如何扫描文件,如果找不到,然后添加一个新文件?

例如:

我运行一次程序。该文件夹为空,因此它将文件添加到名为“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)延迟中的错误的情况下的过程,使我的整个计算机没有超载,并感谢上帝,因为程序只是不断增加越来越多的文件,直到我强迫退出。

+2

模式'a'只会继续并创建文件,即使它不存在,所以你永远不会得到异常。 –

+1

这解决了我的问题。我用“r”替换了我的“a”。 –

回答

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() 

的问题是,如果是同一个程序的多个实例同时运行,一些文件可能会被覆盖。