在Python中反复使用计数器创建文件

基本上我想要做的是编写一个
python脚本,用于创建文件名中带有count-number的文件,例如“file 1.txt”“file 2.txt”“file 3.txt”.

我走到这一步:

import shutil, os, itertools


for i in itertools.count():
    file = open("FILE " + str(i) + ".txt", 'w+')
    print(i)
    time.sleep(1)

基本上我能做的就是数数,但文件创建是我的问题. open()似乎不起作用.如何创建这些文件,如何选择directorys来存储文件?

最佳答案

import shutil, os, itertools
import time

dirpath = 'c:\\usr\\'
for i in itertools.count():
    file = open(dirpath+"FILE " + str(i) + ".txt", 'w+')
    print(i)
    time.sleep(1)

这会奏效.你的代码运行正常.我刚刚添加了目录路径

点赞