在Python中写入文件时增加文件名

在Python中写入文件时增加文件名,python,django,Python,Django,我的代码可以工作并增加文件名,但只对前两个文件有效,然后在现有的第二个文件中创建新字符串。请帮我升级代码以进一步升级 text = 'some text' file_path = '/path/to/file' filename = 'textfile' i = 1 txtfile = self.file_path + filename + str(i) + '.txt' if not os.path.exists(txtfile): text_file = open(txtfile, "

我的代码可以工作并增加文件名,但只对前两个文件有效,然后在现有的第二个文件中创建新字符串。请帮我升级代码以进一步升级

text = 'some text'
file_path = '/path/to/file'
filename = 'textfile'
i = 1
txtfile = self.file_path + filename + str(i) + '.txt'
if not os.path.exists(txtfile):
   text_file = open(txtfile, "a")
   text_file.write(self.text)
   text_file.close()

elif os.path.exists(txtfile) and i >= 1:
   i += 1
   text_file1 = open(self.file_path + filename + str(i) + '.txt', "a")   
   text_file1.write(self.text)
   text_file1.close()

如果您的示例是循环的一部分,则在每次迭代中将
i
重置为
1
。将
i=1
置于该零件外部


当您重新启动程序时,它也将从
1
开始,有时不是您想要的。

如果您的示例是循环的一部分,则在每次迭代中将
i
重置为
1
。将
i=1
置于该零件外部


当你重新启动你的程序时,它也会从
1
开始,有时不是你想要的。

这是在循环中运行吗?是的,当然。它在文本字符串中循环,这是在循环中运行吗?是的,当然。它在文本字符串中循环。为了避免它,我必须在位置中添加对现有文件的额外检查…也许为了避免它,我必须在位置中添加对现有文件的额外检查。。。