2014-01-23 30 views
0

我在写一个小脚本。该脚本创建了.txt文件。我不想替换现有的文件。所以我想要python做的是检查文件是否已经存在。如果没有,它可以继续。如果文件确实存在,我希望python增加名称,并再次检查文件是否已经存在。如果文件不存在,python可能会创建它。 实例: 当前目录中有这些文件:Python - 创建下一个文件

file_001.txt

file_002.txt

我想蟒蛇看到这两个文件存在,使得下一个文件:

file_003.txt

创建文件可以这样完成:

f = open("file_001.txt", "w") 
f.write('something') 
f.close() 

checking文件是否存在:

import os.path 
os.path.isfile(fname) 
+0

'进口操作系统; os.path.exist'可能会有所帮助。 –

+0

我想我可以真正回答我自己的问题。我可以使用一个循环 – Vader

回答

1

下面是一些代码,将完成这项工作,我回答了它自己。

进口os.path中

def next_file(filename): 
    """ 
    filename: string. Name only of the current file 
    returns: string. The name of the next file to be created 
    assumes the padding of the file is filename_001.txt The number of starting zeros does not not matter 
    """ 
    fill_exists = True 
    current = '001' 
    padding = len(current) # length of digits 
    file = '{}_{}.txt'.format(filename, current) # the actual name of the file, inlc. extension 
    while fill_exists: 
     if not os.path.isfile(file): # if the file does not already exist 
      f = open(file, 'w') # create file 
      f.write(filename) 
      f.close() 
      return 'Created new file: {}_{}.txt'.format(filename, current) # shows the name of file just created 
     else: 
      current = str(int(current)+1).zfill(padding) # try the next number 
      file = '{}_{}.txt'.format(filename, current) 
2

如果你想检查它是否是一个既文件和它存在,则使用os.path.existsos.path.isfile一起。或者只是前者似乎就足够了。以下可能会有所帮助:

import os.path as op 
print op.exists(fname) and op.isfile(fname) 

或只是print op.exists(fname)

+0

我也希望python找出哪个是序列中要创建的下一个文件并创建它。 – Vader