2010-03-08 20 views
-1

可能重複:
Python: How do I create sequential file names?的Python:幫助與計數器和寫入文件

我建議使用一個單獨的文件作爲計數器給我的文件順序文件的名稱,但我不明白我會怎麼做。我需要我的文件名具有序列號,如file1.txt,file2.txt,file3.txt。任何幫助表示讚賞!

編輯: 我的錯誤,我忘了說代碼執行時會生成1個文件,並且需要一種方法來創建一個具有不同文件名的獨立文件。

更多編輯: 我正在拍攝一個基本的屏幕截圖,並試圖將其寫入文件,並且我希望能夠在不被覆蓋的情況下拍攝多張照片。

+1

請詳細說明。你是如何創建這些文件的?你想解決什麼問題? –

+1

爲什麼你需要一個計數器文件?你不能只是檢查一個特定的名字是否可用? –

+1

http://stackoverflow.com/questions/2400827/python-how-do-i-create-sequential-file-names – badp

回答

0

是這樣的嗎?

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

假設的例子。

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)) 
2

可能需要更多的信息,但是如果您想按順序命名文件以避免名稱衝突等,您不一定需要單獨的文件來記錄當前的數字。我假設你想不時寫一個新文件,編號來跟蹤事情?

因此給定一組文件,你想知道下一個有效的文件名是什麼。

喜歡的東西(在當前目錄下的文件):

 
import os.path

def next_file_name(): num = 1 while True: file_name = 'file%d.txt' % num if not os.path.exists(file_name): return file_name num += 1

顯然,雖然作爲文件的目錄數量的增加,這將變慢,所以這取決於你有多少個文件,期望有成爲。

0
# 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或更高版本中,您不會(也可以使用比%運算符更優雅的格式化解決方案,但這是一個很小的問題)。