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)延迟中的错误的情况下的过程,使我的整个计算机没有超载,并感谢上帝,因为程序只是不断增加越来越多的文件,直到我强迫退出。
模式'a'只会继续并创建文件,即使它不存在,所以你永远不会得到异常。 –
这解决了我的问题。我用“r”替换了我的“a”。 –