2016-03-28 31 views
0

我很難循環遍歷與腳本編寫目錄不同的目錄中的文件。我最好也希望我的腳本能夠通過所有以sasa開頭的文件。有一些文件夾中的文件,如sasa.1,sasa.2等...以及其他文件,如doc1.pdf,doc2.pdfPython:循環遍歷不同目錄中的文件並掃描數據

我使用Python版本2.7與Windows PowershellC:Users\user\python_project

2)Main_Directory前:C:Users\user\Desktop\Data

一切

1)的Python腳本位置前的

位置

3)Current_Working_Directory例如:C:Users\user\python_project

主目錄中包含100個文件夾(文件夾A,B,C,d等) 每個文件夾的包含許多文件包括感興趣的赤竹文件。

嘗試在運行腳本

對於1個文件中的以下作品:

腳本運行方式如下:python script1.py

file_path = 'C:Users\user\Desktop\Data\A\sasa.1 

def writing_function(file_path): 
    with open(file_path) as file_object: 
     lines = file_object.readlines() 

for line in lines: 
print(lines) 

writing_function(file_path) 

但是,下列不工作

腳本運行以下方式:python script1.py A sasa.1

import os 
import sys 
from os.path import join 

dr = sys.argv[1] 
file_name = sys.argv[2] 

file_path = 'C:Users\user\Desktop\Data' 
new_file_path = os.path.join(file_path, dr) 
new_file_path2 = os.path.join(new_file_path, file_name) 

def writing_function(paths): 
    with open(paths) as file_object: 
     lines = file_object.readlines() 

for line in lines: 
    print(line) 

writing_function(new_file_path2) 

我收到以下錯誤:

with open(paths) as file_object:
IO Error: [Errno 2] No such file or directory:
'C:Users\\user\\Desktop\\A\\sasa.1'

請現在我只是工作一個文件注意,我想通過所有的能夠循環文件夾中的sasa文件。

+0

考慮使用'os.walk' – chapelo

回答

0

它可以是東西線:利用可變dir

import os 
from os.path import join 

def function_exec(file): 
    code to execute on each file 

for root, dirs, files in os.walk('path/to/your/files'): # from your argv[1] 
    for f in files: 
     filename = join(root, f) 
     function_exec(filename) 

避免。它是一個python關鍵字。嘗試print(dir(os))

dir_ = argv[1] # is preferable 
+0

我能否僅傳遞argv中的文件夾名稱,還是必須傳遞整個文件路徑?理想情況下,我只想將文件夾名稱放在參數 我大概可以將代碼中的整個路徑一直到主文件夾,但我想用戶只需將該文件夾的名稱包含這些文件。 –

+0

您可以使用'os.path.join()'加入一個基本目錄,例如您的數據所在的目錄「2)Main_Directory ex:C:Users \ user \ Desktop \ Data」以及您的用戶輸入的目錄。檢查文檔https://docs.python.org/3/library/os.path.html?highlight=join#os.path.join – chapelo

+0

如果該目錄是相對於您當前的目錄,您也可以使用它使用'os.getcwd()' – chapelo

0

另外請注意,您可以使用

os.chdir(path) 
+0

當將文件夾名稱傳遞到目錄時,我嘗試使用os.chdir(folder_name)。我怎麼會在不知道的情況下通過整條路? –

0

沒有人提到glob到目前爲止改變目錄位置,所以: https://docs.python.org/3/library/glob.html

我認爲你可以使用它的**魔力解決您的問題:

If recursive is true, the pattern 「**」 will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.