2013-07-12 25 views
0

我無法將mp4文件從一個目錄移動到另一個目錄(Ubuntu Linux)。當我在目錄之間移動.py文件時,我所包含的代碼似乎能夠完美工作。我對谷歌搜索一個答案做了一些研究,但無濟於事。我已經找到答案指向權限等,我已經從以下網址找到幫助。無法使用python將mp4文件移動到ubuntu中的另一個目錄

http://stackoverflow.com/questions/13193015/shutil-move-ioerror-errno-2-when-in-loop

http://stackoverflow.com/questions/7432197/python-recursive-find-files-and-move-to-one-destination-directory

我是新來的Python和剛學。請你可以協助我提供的代碼以及當我運行我的python腳本移動.mp4文件時得到的錯誤消息。

sudo python defmove.py /home/iain/dwhelper /home/iain/newfolder .mp4

(我運行從哪裏defmove.py腳本所在的目錄中的腳本,我也確信,newfolder不運行defmove.py之前存在)

import os 
import sys 
import shutil 

def movefiles(src,dest,ext): 
    if not os.path.isdir(dest): 
     os.mkdir(dest) 
      for root,dirs,files in os.walk(src): 
       for f in files: 
        if f.endswith(ext): 
         shutil.move(f,dest) 

def main(): 
    if len(sys.argv) != 4: 
     print 'incorrect number of paramaters' 
     sys.exit(1) 
    else: 
     src = sys.argv[1] 
     dest = sys.argv[2] 
     ext = sys.argv[3] 
     movefiles(src,dest,ext) 

main()

Traceback (most recent call last): 
    File "defmove.py", line 24, in <modeule> 
    main() 
    File "defmove.py", line 22, in main 
    movefiles(src,dest,ext) 
    File "defmove.py", line 11, in movefiles 
    shutil.move(f,dest) 
    File "/usr/lib/python2.7/shutil.py", line 301, in move 
    copy2(src, real_dst) 
    File "/usr/lib/python2.7/shutil.py", line 130, in copy2 
    copyfile(src,dest) 
    File "/usr/lib/python2.7/shutil.py", line 82, in copyfile 
    with open(src, 'rb') as fsrc: 
IOError: [Errno 2] No suck file or directory: 'feelslike.mp4' 
+0

謝謝。我只是相應地修改了我的代碼,這一舉動取得了成功。然而,我感到困惑,爲什麼當我將.py文件移動到另一個目錄而不是它的工作.mp4文件。當我試圖移動.mp4文件時,我似乎只能得到上述錯誤信息。你能提供一個解釋這個....? – user1530081

回答

1

當python I/O被賦予文件名時,它假定文件位於當前目錄或其路徑上的某處;如果它不在任何這些地方,則產生IOError。因此,當您訪問除當前目錄以外的目錄中的文件時,指定該文件的路徑很重要。

在你的代碼中,調用shutils.movef只是給函數提供一個文件名---該文件名的路徑已被刪除。因此,您撥打shutils.move應該看起來像

shutil.move(os.path.join(root, f), dest) 
+0

謝謝你的解釋。我現在瞭解如何以及爲什麼當它試圖從我的Python腳本中移動另一個目錄時移動.mp4文件時出錯。 – user1530081

相關問題