2011-04-16 64 views
0

我有一個python工具來'觸摸'(utime)一個文件,然後移動到另一個文件夾。但是,如果該文件已存在於目標文件夾中,則會被無提示地覆蓋。我想檢查一個目標文件夾中的同名文件,如果存在,請將其重命名爲我的名字加'n'結尾,其中n是一個開頭的數字在'1'處,並且如果在末尾具有'-1'的文件已經存在,則'-2'等。
例如,假設在源文件夾中是文件'foo.txt',但是存在' foo.txt'也在目標文件夾中。這個函數應該返回'(絕對路徑)/ foo -1 .txt'。python函數不重複

所以,我已經做了一個函數來檢查這些情況並返回修改的字符串,所以我可以稍後使用重命名而不是覆蓋。但是,目前,如果文件存在,它不會返回任何內容。以下是功能代碼,假設這些變量:

fileName - 輸入文件路徑,絕對路徑。例如/Users/foo/sourceFolder/bar.txt
索引 - 迭代變量,在每個文件的開始設置爲「1」被打開(外部給功能)

def checkExists(fileName): 
    global index 
    print "checkExists(" + fileName + ")" 

    if exists(fileName): 
     splitPath = split(newFile) 
     splitName = splitext(splitPath[1]) 
     newSplitName = splitName[0] + "-" + str(index) 

     index += 1 
     newName = splitPath[0] + "/" + newSplitName + splitName[1] 

     print "newName = " + newName 
    else: 
     print "(else) fileName = " + fileName 
     print "(else) fileName = " + str(type(fileName)) 
     print "" 
     return fileName 

    checkExists(newName) 

目前看來,所述內呼叫checkExists()最後沒有運行。

我希望我的解釋清楚。
IAmThePiGuy

P.S.我不想聽到有關使用時間的潛在競爭問題,我知道源目錄中的文件不會被其他任何內容訪問。

+0

檢查您的壓痕。 – 2011-04-16 02:01:42

回答

2

你的問題是,如果文件存在,你不會返回任何東西。我認爲你打算使用遞歸來檢查新的文件名,但是你不會返回該調用的結果。這裏有一個刺:

def checkExists(fileName, index=0): 
    print "checkExists(" + fileName + ")" 

    if exists(fileName): 
     splitPath = split(newFile) 
     splitName = splitext(splitPath[1]) 
     newSplitName = splitName[0] + "-" + str(index) 

     index += 1 
     newName = splitPath[0] + "/" + newSplitName + splitName[1] 

     print "newName = " + newName 
     return checkExists(newName, index) # recurse 
    else: 
     print "(else) fileName = " + fileName 
     print "(else) fileName = " + str(type(fileName)) 
     print "" 
     return fileName 

我也動了遞歸調用更接近newName產生和清除的全局變量和遞歸取代,作爲井的自由。

+0

謝謝,這就是我正在尋找的東西,我沒有意識到,如果我告訴它自己回來,它會緩解! – cortices 2011-04-16 02:12:19

+0

好吧,它會在任何情況下遞歸,它不會將遞歸的結果返回給原始調用者。一個迭代的解決方案在技術上運行速度會更快,但在您的用例中我懷疑您會注意到。 – kindall 2011-04-16 02:17:04

1

下面是一個迭代的方法進行了類似的問題:

def copyfile(path, dstdir, verbose=True, dryrun=False): 
    """Copy `path` file to `dstdir` directory incrementing name if necessary.""" 
    filename = os.path.basename(path) 
    basename, ext = os.path.splitext(filename) 

    for i in itertools.count(2): 
     destpath = os.path.join(dstdir, filename) 
     if not os.path.exists(destpath): 
      if verbose: 
       print(path, '->', destpath) 
      if not dryrun: 
       shutil.copyfile(path, destpath) 
      return 
     # increment filename 
     filename = "%s_%02d%s" % (basename, i, ext) 
+0

看起來像一個很好的答案,但它的方式超過了我目前在python中的實力:-) – cortices 2011-05-25 08:26:57