-2

Let say I have a folder

/home/me/data/picture/

and picture folder include various of picture files.
if I want to look through all the file inside and get each file name.

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

is it possible how many files in certain folder? and get each file names?

pojo jake
  • 9
  • 2
  • 1
    `os.listdir("some_path")` gives you a list of files in a folder – DavidG Dec 13 '17 at 13:05
  • Possible duplicate of [How to process files from one subfolder to another in each directory using Python?](https://stackoverflow.com/questions/29283466/how-to-process-files-from-one-subfolder-to-another-in-each-directory-using-pytho) – zmo Dec 13 '17 at 13:06

3 Answers3

0

or you can use:

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

or you can use os.walk to iterate over all the paths within a given directory:

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

or you can use a glob.

zmo
  • 24,463
  • 4
  • 54
  • 90
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)

result is a list, which contains all files in a certain folder

bierschi
  • 322
  • 3
  • 11
0

You may want to have a look at 15.1. os — Miscellaneous operating system interfaces and 10.1. os.path — Common pathname manipulations

In your case, you can use os.listdir(path), which returns a list of all your files in given folder.

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)

for more operations, you may want to look to this functions:

os.environ(path), for the pathname of your home directory.

os.chdir(path), for changing directory

os.getcwd(), for your current directory

os.join(path, *paths), join paths

and many others like mkdir, makedirs, remove, removedirs and those from pathname manipulations, like path.basename, path.dirname, path.exist, path.isfile, path.isdir...

Gsk
  • 2,929
  • 5
  • 22
  • 29