【问题标题】:Python: Help with counters and writing files [duplicate]Python:帮助计数器和写入文件[重复]
【发布时间】:2010-03-08 23:59:03
【问题描述】:

可能重复:
Python: How do I create sequential file names?

有人建议我使用一个单独的文件作为计数器来为我的文件提供连续的文件名,但我不明白该怎么做。我需要我的文件名有序列号,例如 file1.txt、file2.txt、file3.txt。任何帮助表示赞赏!

编辑: 我的错误,我忘了说代码在执行时会生成一个文件,并且需要一种方法来创建一个具有不同文件名的新文件。

更多编辑: 我基本上是在拍摄屏幕截图并尝试将其写入文件,并且我希望能够拍摄多个而不被覆盖。

【问题讨论】:

  • 请详细说明。你是如何创建文件的?您要解决的问题是什么?
  • 为什么需要计数器文件?你不能只检查一个特定的名字是否可用吗?

标签: python filesystems


【解决方案1】:

可能需要更多信息,但如果您想按顺序命名文件以避免名称冲突等,则不一定需要单独的文件来记录当前编号。我假设您想不时编写一个新文件,编号以跟踪事情?

所以给定一组文件,你想知道下一个有效的文件名是什么。

类似(对于当前目录中的文件):

import os.path

定义下一个文件名(): 数 = 1 而真: 文件名 = 'file%d.txt' % 数量 如果不是 os.path.exists(file_name): 返回文件名 数字 += 1

显然,随着目录中文件数量的增加,这会变慢,所以这取决于您期望有多少文件。

【讨论】:

    【解决方案2】:

    这样的?

    n = 100
    for i in range(n):
      open('file' + str(i) + '.txt', 'w').close()
    

    【讨论】:

      【解决方案3】:

      假设的例子。

      import os
      counter_file="counter.file"
      if not os.path.exists(counter_file):
          open(counter_file).write("1");
      else:
          num=int(open(counter_file).read().strip()) #read the number
      # do processing...
      outfile=open("out_file_"+str(num),"w")
      for line in open("file_to_process"):
          # ...processing ...
          outfile.write(line)    
      outfile.close()
      num+=1 #increment
      open(counter_file,"w").write(str(num))
      

      【讨论】:

        【解决方案4】:
        # get current filenum, or 1 to start
        try:
          with open('counterfile', 'r') as f:
            filenum = int(f.read())
        except (IOError, ValueError):
          filenum = 1
        
        # write next filenum for next run
        with open('counterfile', 'w') as f:
          f.write(str(filenum + 1))
        
        filename = 'file%s.txt' % filenum
        with open(filename, 'w') as f:
          f.write('whatever you need\n')
          # insert all processing here, write to f
        

        在 Python 2.5 中,您还需要第一行 from __future__ import with_statement 才能使用此代码示例;在 Python 2.6 或更高版本中,您不需要(您也可以使用比 % 运算符更优雅的格式化解决方案,但这是一个非常小的问题)。

        【讨论】:

          猜你喜欢
          • 2015-06-11
          • 2018-07-28
          • 2017-01-03
          • 1970-01-01
          • 2011-10-15
          • 2015-05-20
          • 1970-01-01
          • 2015-12-13
          • 2021-06-06
          相关资源
          最近更新 更多