【问题标题】:Repeatedly create files with counter in Python在 Python 中使用计数器重复创建文件
【发布时间】:2016-12-02 14:10:21
【问题描述】:

基本上我想做的是编写一个 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() 似乎不起作用。如何创建这些文件以及如何选择存储文件的目录?

【问题讨论】:

  • 您要创建文件吗?
  • 在我的机器上工作。 Python 3.3 您必须使用os.chdir导航到要在其中创建文件的目录
  • 你可以尝试closefor循环中的文件。

标签: python text-files itertools


【解决方案1】:
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)

这会奏效。而且您的代码工作正常。我只是添加了目录路径

【讨论】:

  • 该死的我只需要一条路径...不过还是谢谢!!
【解决方案2】:

如果您使用 Python 3.4+,请尝试pathlib.Path(...).touch

import os
from pathlib import Path
import itertools

for i in itertools.count():
    filename = ''.join(['FILE', str(i), '.txt'])
    Path(os.path.join(dir, filename).touch()

Python2 中,我认为使用with statement 更好。

import os
import itertools

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

【讨论】:

    【解决方案3】:
    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()
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2017-04-16
      • 2012-09-21
      • 2012-10-07
      • 2018-12-10
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多