如何查看某个文件夹中的文件?

时间:2017-12-13 13:03:06

标签: python file

假设我有一个文件夹

/home/me/data/picture/

和图片文件夹包括各种图片文件。
如果我想查看里面的所有文件并获取每个文件名。

while file in fileexist:
   y,sr = somefunction.load("/home/me/data/picture"+file.name);

是否有可能在某个文件夹中有多少个文件?并获取每个文件名?

3 个答案:

答案 0 :(得分:0)

或者您可以使用:

for file in os.listdir(folder):
    print(os.path.join(folder, file))

或者您可以使用os.walk迭代给定目录中的所有路径:

folder='/home/me/data/picture'
for path, subdirs, files in os.walk(folder):
    for file in files:
        print(os.path.join(path, file))

或者您可以使用glob。

答案 1 :(得分:0)

from os import listdir
from os.path import isfile, join

files_list = [f for f in listdir('your_path/to_folder') if isfile(join('your_path/to_folder', f))]

print(files_list)

结果是一个列表,其中包含特定文件夹中的所有文件

答案 2 :(得分:0)

您可能需要查看15.1. os — Miscellaneous operating system interfaces10.1. os.path — Common pathname manipulations

在您的情况下,您可以使用os.listdir(path),它返回给定文件夹中所有文件的列表。

import os

path = "C:/home/me/data/picture" # full path to folder

# You can print the number of the file in the folder with
# the functions len() and os.listdir()
print(len(os.listdir(path)))

# You can get the list of the files in the folder with:
print(os.listdir(path))

# if you want a more readable outcome, print each file with for loop:
for file in os.listdir(path):
print(file)

如需更多操作,您可能需要查看此功能:

os.environ(path),用于主目录的路径名。

os.chdir(path),用于更改目录

os.getcwd(),对于您当前的目录

os.join(path, *paths),加入路径

和许多其他人一样,如mkdir,makedirs,remove,removedirs 以及来自路径名操作的那些,例如path.basename,path.dirname,path.exist,path.isfile,path.isdir ......