Python:循环在python中打开多个文件夹和文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:循环在python中打开多个文件夹和文件相关的知识,希望对你有一定的参考价值。
我是python的新手,目前从事数据分析工作。
我试图在循环中打开多个文件夹并读取文件夹中的所有文件。防爆。工作目录包含打开所需的10个文件夹,每个文件夹包含10个文件。
我的代码用.txt文件打开每个文件夹;
file_open = glob.glob("home/....../folder1/*.txt")
我想打开文件夹1并读取所有文件,然后转到文件夹2并读取所有文件...直到文件夹10并读取所有文件。任何人都可以帮我如何编写循环打开文件夹,包含需要使用的库?
我在R中有我的背景,例如,在R中,我可以编写循环来打开文件夹,文件使用下面的代码。
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
答案
此递归方法将扫描给定目录中的所有目录,然后打印txt
文件的名称。我诚挚地邀请你继续前进。
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recall this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
另一答案
我认为很好的方法是使用os.walk。这将生成树,然后您可以遍历该树。
import os
directory = './'
for d in os.walk(directory):
print(d)
另一答案
给定以下文件夹/文件树:
C:.
├───folder1
│ file1.txt
│ file2.txt
│ file3.csv
│
└───folder2
file4.txt
file5.txt
file6.csv
以下代码将以递归方式查找树中的所有.txt
文件:
import os
import fnmatch
for path,dirs,files in os.walk('.'):
for file in files:
if fnmatch.fnmatch(file,'*.txt'):
fullname = os.path.join(path,file)
print(fullname)
输出:
.\folder1\file1.txt
.\folder1\file2.txt
.\folder2\file4.txt
.\folder2\file5.txt
另一答案
你的glob()
模式几乎是正确的。尝试以下方法之一:
file_open = glob.glob("home/....../*/*.txt")
file_open = glob.glob("home/....../folder*/*.txt")
第一个将检查home/......
的任何第一级子目录中的所有文本文件,无论是什么。第二个将限制为名为“folder1”,“folder2”等的子目录。
我不会说R,但这可能会翻译你的代码:
for filename in glob.glob("......../main/*/*.txt"):
with open(filename) as file_handle:
for line in file_handle:
# perform data on each line of text
另一答案
此代码将查找目录中的所有目录,并打印出在那里找到的所有文件的名称:
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: print filenames one level down from starting folder
#--------*---------*---------*---------*---------*---------*---------*---------*
import os, fnmatch, sys
def find_dirs(directory, pattern):
for item in os.listdir(directory):
if os.path.isdir(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
def find_files(directory, pattern):
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
#--------*---------*---------*---------*---------*---------*---------*---------#
while True:# M A I N L I N E #
#--------*---------*---------*---------*---------*---------*---------*---------#
# # Set directory
os.chdir("C:\\Users\\Mike\\\Desktop")
for filedir in find_dirs('.', '*'):
print ('Got directory:', filedir)
for filename in find_files(filedir, '*'):
print (filename)
sys.exit() # END PROGRAM
以上是关于Python:循环在python中打开多个文件夹和文件的主要内容,如果未能解决你的问题,请参考以下文章