我很难循环遍历与脚本编写目录不同的目录中的文件。我最好也希望我的脚本能够通过所有以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文件。
考虑使用'os.walk' – chapelo