如何列出目录的所有文件?
我如何列出Python中的目录的所有文件,并将它们添加到list ? 
  os.listdir()将会为你提供目录中的所有东西 – 文件和目录。 
 如果你只想要文件,你可以使用os.path来过滤掉它: 
 from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] 
 或者你可以使用os.walk() ,它会为每个访问目录产生两个列表 – 分割成文件和目录。 如果你只想要最上面的目录,你可以在第一次打破的时候打破它 
 from os import walk f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break 
 最后,正如这个例子所示,添加一个列表到另一个你可以使用.extend()或 
 >>> q = [1, 2, 3] >>> w = [4, 5, 6] >>> q = q + w >>> q [1, 2, 3, 4, 5, 6] 
 就个人而言,我更喜欢.extend() 
 我更喜欢使用glob模块,因为它可以进行模式匹配和扩展。 
 import glob print(glob.glob("/home/adam/*.txt")) 
将返回一个列表与查询的文件:
 ['/home/adam/file1.txt', '/home/adam/file2.txt', .... ] 
 import os os.listdir("somedirectory") 
将返回“somedirectory”中的所有文件和目录的列表。
用当前目录的文件获取列表的最快方法 – Python 3
 >>> import os >>> arr = os.listdir() >>> arr ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents'] 
用当前目录的文件获取列表的最快方法 – Python 2
 >>> import os >>> arr = os.listdir('.') >>> arr ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents'] 
只需在当前目录中使用os.walk('。')即可
 >>> import os >>> arr = next(os.walk('.'))[2] >>> arr ['5bs_Turismo1.pdf', '5bs_Turismo1.pptx', 'esperienza.txt'] 
快速获取当前目录中文件的完整path
 >>> import os >>> path = os.getcwd() >>> arr = [] >>> for files in next(os.walk(path))[2]: >>> arr.append(path + "\\" + files) ... >>> for files in arr: >>> print(files) ... F:\_moduli_economia\5bs_Turismo1.pdf F:\_moduli_economia\5bs_Turismo1.pptx F:\_moduli_economia\esperienza.txt 
更深入的了解:如何获取Python 2和Python 3中的文件列表?
这里是我在这个答案中谈到的一个列表:
操作系统。 listdir ()为Python 3 
- 1.1 – 使用列表理解select仅txt文件
- 1.2 – 使用操作系统。 path.isfile避免列表中的目录
pathlib 操作系统。 走 () 操作系统。 scandir () python 2( os。listdir ()) 
4.1 – python 2.7 – os。 走 ('。') 使用os的例子 walk ('。')来计算一个目录及其子目录中有多less个文件(对于python 3.5和2.7) 使用glob 奖金:search一种文件并将其复制到一个目录中 
1. os.listdir()(python 3)
 >>> import os >>> arr = os.listdir() >>> arr ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents'] 
1.1 – 使用列表理解select仅txt文件
 >>> arr_txt = [x for x in os.listdir() if x.endswith(".txt")] >>> print(arr_txt) ['work.txt', '3ebooks.txt'] 
1.2 – 使用os.path.isfile来避免列表中的目录
 import os.path listOfFiles = [f for f in os.listdir() if os.path.isfile(f)] print(listOfFiles) 
产量
这里只有文件
['简单的game.py','data.txt','decorator.py','deep_reverse_list.py','deep_reverse_list2.py','hangman.py','import pygame.py','list_click_display.py ','os_path.py']
2. Python 3.4 [pathlib]
 import pathlib >>> flist = [] >>> for p in pathlib.Path('.').iterdir(): ... if p.is_file(): ... print(p) ... flist.append(p) ... error.PNG exemaker.bat guiprova.mp3 setup.py speak_gui2.py thumb.PNG 
如果你想使用列表理解
 >>> flist = [p for p in pathlib.Path('.').iterdir() if p.is_file()] 
3. Python 3.5(和2.7)[os.walk]
要包含子目录中的所有文件(在这个例子中,第一个目录中有11个文件,子目录中有3个文件),我将使用os.walk(),它可以在python 3.5和更新版本中使用:
 import os x = [i[2] for i in os.walk('.')] y=[] for t in x: for f in t: y.append(f) print(y) # print y # for 2.7 uncomment this and comment the previous line 
产量
data_txt,data2.txt,data_180617,os_walk.py,READ2.py,read_data.py,somma_defaltdic。 py','substitute_words.py','sum_data.py','data.txt','data1.txt','data_180617']
– 只有下一个文件,走在一个目录
 >>> import os >>> next(os.walk('F://python'))[2] # for the current dir use ('.') ['calculator.bat','calculator.py'] 
– 只获取下一个目录并走到目录中
 >>> import os >>> next(os.walk('F://python'))[1] # for the current dir use ('.') ['python3','others'] 
– 下一步获取根目录,并在目录中走
 >>> import os >>> next(os.walk('F://python'))[0] # for the current dir use ('.') 'F://python' 
4. os.scandir()从python 3.5开始
 >>> import os >>> x = [f.name for f in os.scandir() if f.is_file()] >>> x ['calculator.bat','calculator.py'] 
scandir的另一个例子(与docs.python.org稍有不同)这个比os.listdir更高效。 在这种情况下,它只显示脚本执行的当前目录中的文件。
 >>> import os >>> with os.scandir() as i: ... for entry in i: ... if entry.is_file(): ... print(entry.name) ... ebookmaker.py error.PNG exemaker.bat guiprova.mp3 setup.py speakgui4.py speak_gui2.py speak_gui3.py thumb.PNG >>> 
5. Python 2
使用getcwd()获取当前工作目录在Python 2(或('。'))
 >>> import os >>> mylist = os.listdir(os.getcwd()) >>> mylist ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents'] 
要进入目录树,你需要这样的代码:
 >>> for f in os.listdir('..'): ... print f >>> for f in os.listdir('/'): ... print f 
具有绝对path的文件列表
这和Python 3是一样的(除了打印)
 >>> x = os.listdir('F:/python') >>> for files in x: >>> print files ... $RECYCLE.BIN work.txt 3ebooks.txt documents 
5.1 – python 2 – os.walk('。')
让我们用python 2.7来做一个例子(和python 3一样)。
 >>> def getAllFiles(dir): ... """Get all the files in the dir and subdirs""" ... allfiles = [] ... for pack in os.walk(dir): ... for files in pack[2]: ... if os.path.isfile(files): ... allfiles += [files] ... return allfiles ... >>> getAllFiles("F://python") ['first.py', 'Modules.txt', 'test4Console.py', 'text4Console.bat', 'tkinter001.py'] 
6.为python 3.5和2.7使用os.walk('。')的例子
在这个例子中,我们查找包含在所有目录及其子目录中的文件数量。
 import os def count(dir, counter=0): "returns number of files in dir and subdirs" for pack in os.walk(dir): for f in pack[2]: counter += 1 return dir + " : " + str(counter) + "files" print(count("F:\\python")) 
产量
'F:\\ python':12057 files'
7.使用glob
 >>> import glob >>> glob.glob("*.txt") ['ale.txt', 'alunni2015.txt', 'assenze.text.txt', 'text2.txt', 'untitled.txt'] 
8.奖金:find文件并将其复制到目的地
一个小脚本,在一些目标的所有子目录中进行search(我select那些在开始时具有不良符号的目录),将所有types的文件(pdf或pptx或txt ecc)复制到目标目录中。 如果你做了很多子目录,并且想要看看你所做的所有的东西,那么这很有用。让我们在一个地方说一下演示文稿,而不必回忆你把这个文件放在哪里。 我希望你觉得有帮助。 我用于我自己的目的。
 import os import shutil from path import path destination = "F:\\pptx_copied" # os.makedirs(destination) def copyfile(dir, filetype='pptx', counter=0): "Searches for pptx (or other) files and copies them" for pack in os.walk(dir): for f in pack[2]: if f.endswith(filetype): fullpath = pack[0] + "\\" + f print(fullpath) shutil.copy(fullpath, destination) counter += 1 if counter > 0: print("------------------------") print("\t==> Found in: `" + dir + "` : " + str(counter) + " files\n") for dir in os.listdir(): "searches for folders that starts with `_`" if dir[0] == '_': # copyfile(dir, filetype='pdf') copyfile(dir, filetype='txt') 
产量
 _compiti18\Compito Contabilità 1\conti.txt _compiti18\Compito Contabilità 1\modula4.txt _compiti18\Compito Contabilità 1\moduloa4.txt _compiti18\ottobre\3acc\compito.txt _compiti18\ottobre\3acc\compito1530.txt _compiti18\ottobre\3acc\compito1530_correttore.txt _compiti18\ottobre\3acc\compito3825.txt _compiti18\ottobre\3acc\compito3825_correttore.txt _compiti18\ottobre\3acc\compito6028.txt ------------------------ ==> Found in: `_compiti18` : 9 files 
单行解决scheme来获取文件列表 (无子目录):
 filenames = next(os.walk(path))[2] 
或绝对path名称:
 paths = [os.path.join(path,fn) for fn in next(os.walk(path))[2]] 
从目录及其所有子目录获取完整的文件path
 import os def get_filepaths(directory): """ This function will generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). """ file_paths = [] # List which will store all of the full filepaths. # Walk the tree. for root, directories, files in os.walk(directory): for filename in files: # Join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # Add it to the list. return file_paths # Self-explanatory. # Run the above function and store its results in a variable. full_file_paths = get_filepaths("/Users/johnny/Desktop/TEST") 
- 我在上面的函数中提供的path包含3个文件,其中两个在根目录中,另一个在子文件夹中,名为“SUBFOLDER”。 你现在可以做这样的事情:
- 
print full_file_paths将打印列表的print full_file_paths:-  ['/Users/johnny/Desktop/TEST/file1.txt', '/Users/johnny/Desktop/TEST/file2.txt', '/Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat']
 
-  
如果你愿意,你可以打开并阅读内容,或只关注扩展名为“.dat”的文件,如下面的代码所示:
 for f in full_file_paths: if f.endswith(".dat"): print f 
 /Users/johnny/Desktop/TEST/SUBFOLDER/file3.dat 
 从3.4版本开始,内置的迭代器比os.listdir()更有效率: 
  pathlib : 版本3.4中的新function。 
 >>> import pathlib >>> [p for p in pathlib.Path('.').iterdir() if p.is_file()] 
 根据PEP 428 , pathlib库的目标是提供一个简单的类层次结构来处理文件系统path以及用户对它们进行的常规操作。 
  os.scandir() : 3.5版本中的新function。 
 >>> import os >>> [entry for entry in os.scandir('.') if entry.is_file()] 
 请注意os.walk()使用os.scandir()而不是os.listdir()从3.5版本开始,根据PEP 471 ,它的速度提高了2-20倍。 
我还build议阅读下面的ShadowRanger的评论。
 我真的很喜欢adamk的回答 ,build议您使用同名的模块中的glob() 。 这使您可以与* s进行模式匹配。 
 但正如其他人在评论中指出的那样, glob()可能因不一致的斜杠方向而被绊倒。 为了达到这个目的,我build议你在os.path模块中使用join()和expanduser()函数,也可以在os模块中使用getcwd()函数。 
作为例子:
 from glob import glob # Return everything under C:\Users\admin that contains a folder called wlp. glob('C:\Users\admin\*\wlp') 
以上是可怕的 – path已经硬编码,并将只能在Windows之间的驱动器名称和硬编码的path。
 from glob import glob from os.path import join # Return everything under Users, admin, that contains a folder called wlp. glob(join('Users', 'admin', '*', 'wlp')) 
 上面的工作比较好,但是它依赖于在Windows上经常使用的文件夹名称,在其他操作系统上不常见。 它也依赖于具有特定名称的用户admin 。 
 from glob import glob from os.path import expanduser, join # Return everything under the user directory that contains a folder called wlp. glob(join(expanduser('~'), '*', 'wlp')) 
这适用于所有平台。
另一个很好的例子,跨平台完美工作,做一些有点不同:
 from glob import glob from os import getcwd from os.path import join # Return everything under the current directory that contains a folder called wlp. glob(join(getcwd(), '*', 'wlp')) 
希望这些例子能够帮助您看到在标准Python库模块中可以find的一些function。
 def list_files(path): # returns a list of names (with extension, without full path) of all files # in folder path files = [] for name in os.listdir(path): if os.path.isfile(os.path.join(path, name)): files.append(name) return files 
 你应该使用os模块列出目录内容。  os.listdir(".")返回目录的所有内容。 我们遍历结果并追加到列表中。 
 import os content_list = [] for content in os.listdir("."): # "." means current directory content_list.append(content) print content_list 
 import os lst=os.listdir(path) 
os.listdir返回一个包含path给出的目录中的条目名称的列表。
如果你正在寻找Python的Python实现,这是我经常使用的一个配方:
 from findtools.find_files import (find_files, Match) # Recursively find all *.sh files in **/usr/bin** sh_files_pattern = Match(filetype='f', name='*.sh') found_files = find_files(path='/usr/bin', match=sh_files_pattern) for found_file in found_files: print found_file 
所以我做了一个PyPI 包 ,还有一个GitHub仓库 。 我希望有人发现这个代码可能有用。
  Python 3.5引入了新的,更快的方法来遍历目录 – os.scandir() 。 
例:
 for file in os.scandir('/usr/bin'): line = '' if file.is_file(): line += 'f' elif file.is_dir(): line += 'd' elif file.is_symlink(): line += 'l' line += '\t' print("{}{}".format(line, file.name)) 
返回一个绝对文件path的列表,不recursion到子目录
 L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))] 
列出目录中的所有文件:
 import os from os import path files = [x for x in os.listdir(directory_path) if path.isfile(directory_path+os.sep+x)] 
在这里,您将获得目录中所有文件的列表。
 # -** coding: utf-8 -*- import os import traceback print '\n\n' def start(): address = "/home/ubuntu/Desktop" try: Folders = [] Id = 1 for item in os.listdir(address): endaddress = address + "/" + item Folders.append({'Id': Id, 'TopId': 0, 'Name': item, 'Address': endaddress }) Id += 1 state = 0 for item2 in os.listdir(endaddress): state = 1 if state == 1: Id = FolderToList(endaddress, Id, Id - 1, Folders) return Folders except: print "___________________________ ERROR ___________________________\n" + traceback.format_exc() def FolderToList(address, Id, TopId, Folders): for item in os.listdir(address): endaddress = address + "/" + item Folders.append({'Id': Id, 'TopId': TopId, 'Name': item, 'Address': endaddress }) Id += 1 state = 0 for item in os.listdir(endaddress): state = 1 if state == 1: Id = FolderToList(endaddress, Id, Id - 1, Folders) return Id print start() 
使用发电机
 import os def get_files(search_path): for (dirpath, _, filenames) in os.walk(search_path): for filename in filenames: yield os.path.join(dirpath, filename) list_files = get_files('.') for filename in list_files: print(filename) 
 import dircache list = dircache.listdir(pathname) i = 0 check = len(list[0]) temp = [] count = len(list) while count != 0: if len(list[i]) != check: temp.append(list[i-1]) check = len(list[i]) else: i = i + 1 count = count - 1 print temp 
 如果您关心性能,请尝试scandir ,对于Python 2.x,您可能需要手动安装它。 例子: 
 # python 2.x import scandir import sys de = scandir.scandir(sys.argv[1]) while 1: try: d = de.next() print d.path except StopIteration as _: break 
这样可以节省大量的时间,当你需要扫描一个巨大的目录时,你不需要缓冲一个庞大的列表,只需要一个一个的读取。 而且你也可以recursion地做到这一点:
 def scan_path(path): de = scandir.scandir(path) while 1: try: e = de.next() if e.is_dir(): scan_path(e.path) else: print e.path except StopIteration as _: break 
如果您想要不同的文件types或获取完整的目录,请使用此function。
 import os def createList(foldername, fulldir = True, suffix=".jpg"): file_list_tmp = os.listdir(foldername) #print len(file_list_tmp) file_list = [] if fulldir: for item in file_list_tmp: if item.endswith(suffix): file_list.append(os.path.join(foldername, item)) else: for item in file_list_tmp: if item.endswith(suffix): file_list.append(item) return file_list 
 通过使用os库。 
 import os for root, dirs,files in os.walk("your dir path", topdown=True): for name in files: print(os.path.join(root, name)) 
 import os os.listdir(path) 
这将返回列出path中的所有文件和目录
 filenames = next(os.walk(path))[2] 
这将只返回文件列表而不是子目录
参考@adamk的答案,这里是我的操作系统检测方法,以回应斜线不一致评论由@Anti地球
 import sys import os from pathlib import Path from glob import glob platformtype = sys.platform if platformtype == 'win32': slash = "\\" if platformtype == 'darwin': slash = "/" # TODO: How can I list all files of a directory in Python and add them to a list? # Step 1 - List all files of a directory # Method 1: Find only pre-defined filetypes (.txt) and no subfiles, answer provided by @adamk dir1 = "%sfoo%sbar%s*.txt" % (slash) _files = glob(dir1) # Method 2: Find all files and no subfiles dir2 = "%sfoo%sbar%s" % (slash) _files = (x for x in Path("dir2").iterdir() if x.is_file()) # Method 3: Find all files and all subfiles dir3 = "%sfoo%sbar" % (slash) _files = (x for x in Path('dir3').glob('**/*') if x.is_file()) # Step 2 - Add them to a list files_list = [] for eachfiles in _files: files_basename = os.path.basename(eachfiles) files_list.append(files_basename) 
 print(files_list) ['file1.txt', 'file2.txt', .... ] 
我假设你只想在列表中的基名。
参考这篇文章为方法1预定义多种文件格式。
这是一个简单的例子:
 import os root, dirs, files = next(os.walk('.')) for file in files: print(file) # In Python 3 use: file.encode('utf-8') in case of error. 
  注意:更改.  到你的path值或variables。 
这里是返回具有绝对path的文件列表的例子:
 import os path = '.' # Change this as you need. abspaths = [] for fn in os.listdir(path): abspaths.append(os.path.abspath(os.path.join(path, fn))) print("\n".join(abspaths)) 
 文档:Python 2的os和os.path ,Python 3的os和os.path 。 
 ls -a 
这将列出甚至隐藏的东西。