Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用计数器重复创建文件_Python_Text Files_Itertools - Fatal编程技术网

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

在Python中使用计数器重复创建文件,python,text-files,itertools,Python,Text Files,Itertools,基本上,我想做的是编写一个python脚本,创建文件名中带有计数的文件,例如,“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) 基本上我可以做的是计数,但文件创建是我的问题。o

基本上,我想做的是编写一个python脚本,创建文件名中带有计数的文件,例如,
“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()似乎不起作用。如何创建这些文件以及如何选择存储文件的目录

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)

这会奏效的。你的代码运行良好。我刚刚添加了目录路径

如果您使用的是Python 3.4+,请尝试


在Python2中,我认为使用更好

import os
import itertools

for i in itertools.count():
    filename = ''.join(['FILE', str(i), '.txt'])
    with open(os.path.join(dir, filename), 'w'):
        pass
导入操作系统
数字=0
有效=错误
虽然无效:
usrInput=原始输入(“多少糖果:”)
尝试:
int(usrInput)
有效=真
除:
打印“烛光数!!”
通过
当数字

我希望这有帮助

您想创建空文件吗?我的机器上可能存在重复的工作。Python3.3您必须导航到您想要使用
os.chdir创建文件的目录,您可以尝试
关闭
for
循环中的
文件。该死的,我只需要一个路径。。。谢谢你!!
import os
import itertools

for i in itertools.count():
    filename = ''.join(['FILE', str(i), '.txt'])
    with open(os.path.join(dir, filename), 'w'):
        pass
import os

number = 0
valid = False
while not valid:
    usrInput = raw_input("How much candy?: ")
    try:
        int(usrInput)
        valid = True
    except:
        print "NUMBER of candys!!"
        pass
 while number < int(usrInput):
    number +=1 
    createFile = open('P:/' + str(number) + '.txt', 'w+')
    createFile.write("whatever you want")
    createFile.close()