2017年4月16日 星期日

[ Python 常見問題 ] How to list all files of a directory?

Source From Here 
Question 
How can I list all files of a directory in python and add them to a list? 

How-To 
os.listdir() will get you everything that's in a directory - files and directories. If you want just files, you could either filter this down using os.path
>>> from os import listdir
>>> from os.path import isfile, join
>>> onlyfiles = [f for f in listdir(".") if isfile(join(".", f))] // Collect only file not directory
>>> for f in onlyfiles: print("%s" % (f)) // Print out the collection
...
essay_baseline.py
pos_one_gram_dict
...

or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and dirs for you. If you only want the top directory you can just break the first time it yields: 
  1. from os import walk  
  2.   
  3. f = []  
  4. for (dirpath, dirnames, filenames) in walk(mypath):  
  5.     f.extend(filenames)  
  6.     break  
Supplement 
[ Python 文章收集 ] 常見檔案操作範例

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...