2016-08-21 207 views
-1

找到一種方法來運行一堆子文件夾來查找和移動特殊文件類型到另一個目標,我想過使用python。Python初學者:使用sys.argv處理腳本調用中的文件路徑[

我在OSX工作運行的Python 3

我想運行我的腳本如下:

$python3 find_files.py <search_path> <destination_path> <file_extension> 

如:

$python3 find_files.py /Volumes/Macintosh\ HD/Users/xyz/Downloads/ /Volumes/Data/Files/ zip 

不幸的是,我絕對不知道如何處理文件路徑中的空格。

這裏是我的腳本:

import os, sys, shutil 

def find_files(path, destination, extension): 
    for root, dirs, files in os.walk(path): 
     for file in files: 
      if file.endswith(extension): 
       shutil.move(repr(path)+file, repr(destination)+file) 

find_files(sys.argv[1], sys.argv[2], sys.argv[3]) 

的文件的移動不工作與文件路徑的問題所致。

FileNotFoundError: [Errno 2] No such file or directory: 

我已經嘗試做的東西一樣

form_path = path.replace(' ', '\') 

sys.argv[1] = sys.argv[1].replace(' ', '\\') 

逃避的空間,但我總是得到FileNotFound錯誤。

任何人都可以幫忙嗎?

在此先感謝。

問候 Gardinero

+0

與你的問題無關,但我會說使用bash終端可能是一個更簡單的方法來做到這一點。 – gowrath

回答

0

我覺得你的問題是不是與空間逃逸,而是你的程序;你不會將根追加到你想移動的文件(你不能追加它的路徑,因爲你正在走子目錄)。試試這個:

import os, sys, shutil 

def find_files(path, destination, extension): 
    for root, dirs, files in os.walk(path): 
     for file in files: 
      if file.endswith(extension): 
       shutil.move(root + '/' + file, destination + '/' + file) 


find_files(sys.argv[1], sys.argv[2], sys.argv[3]) 
+0

非常感謝!完善。 – Gardinero