2014-11-07 65 views
-1

我試圖創建多個子目錄和文件移動到這些子目錄,子目錄下的文件的是哪個環路的數量,這是我所:創建多個目錄

for x in range(1,20): 
    os.makedirs('{}/'.format(replace)+str(x)+'/') 
    shutil.move(filename,'{}/'.format(replace)+str(x)+'/') 
    shutil.move(filename1,'{}/'.format(replace)+str(x)+'/') 

我得到這個錯誤:

File "testdraft.py", line 285, in findReplace 
    shutil.move(f, '{}/'.format(replace)+str(x)+'/') 
    File "/usr/lib/python2.7/shutil.py", line 284, in move 
    if _samefile(src, dst): 
    File "/usr/lib/python2.7/shutil.py", line 58, in _samefile 
    return os.path.samefile(src, dst) 
    File "/usr/lib/python2.7/posixpath.py", line 162, in samefile 
    s1 = os.stat(f1) 
TypeError: coercing to Unicode: need string or buffer, file found 

感謝您的幫助

+0

請告訴我們什麼' f'要麼打印出它的'repr',要麼顯示產生它的代碼,或者理想的是兩者。否則,這不是[完整示例](http://stackoverflow.com/help.mcve),只能通過猜測來回答。 – abarnert 2014-11-07 01:34:48

回答

0

想必你f文件對象,而不是文件名。

您實際上未向我們展示任何代碼,其調用shutil.movef;你反而向我們展示了一些代碼,這些代碼用名爲filename1的東西調用它。但是,變量的名稱並不重要;如果它返回的文件對象(例如open函數)存在,則不能將其與move一起使用。

希望,你真正的代碼是一樣的東西一樣簡單:

with open(out_path, 'w') as f: 
    write_data(f) 
shutil.move(f, '{}/'.format(replace)+str(x)+'/') 

然後你只是想改變f在最後一行out_path,就大功告成了。

0

它看起來像你的文件名或filename1變量實際上不是文件名,而是文件對象。 (這是什麼,「文件中找到」在你的錯誤結束時想告訴你。)

此外,你可能要考慮不首先使目錄:

shutil.move(src, dst):

The destination directory must not already exist. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.