2016-03-28 115 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.

相关问题