List files from a Python folder

Asked

Viewed 36,247 times

14

I’d like to know how I use the library os to list files from a given directory.

  • 3

    Give more details about the difficulties encountered, and your questions/problems about performing a specific task.

4 answers

14

os.listdir. You pass a path (relative or absolute) and it gives you the names of all the files, folders and links contained in it. There you can filter by file if you want (using os.path.isfile), or by other criteria:

import os

caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]
jpgs = [arq for arq in arquivos if arq.lower().endswith(".jpg")]

Note: if you are using Python 2, and pass a common string (and not one unicode), results will come as common strings, which can cause problems if there are files with accents in the name. It is therefore recommended to use Unicode in all operations, explicitly converting to unicode if in doubt as to the type.

5

Hello. The package os, offers a range of possibilities.

recursive path + file

import os

def files_path04(path):
    for p, _, files in os.walk(os.path.abspath(path)):
        file in files:
            print(os.path.join(p, file)))

files_path04('/tmp')

An example for multiple directories:

def files_path05(*args):
    for item in args:
        for p, _, files in os.walk(os.path.abspath(item)):
            for file in files:
                print(os.path.join(p, file))

files_path05('/home', '/tmp')

You can still configure a return with a string list, containing the file or a tuple by separating the path and file.

def files_path06(*args):
    l = []
    for item in args:
        for p, _, files in os.walk(os.path.abspath(item)):
            for file in files:
                l.append((p, file))
    return l

files_path06('/home', '/tmp')

Listing through comprehension list

def files_path09(path):
    '''return list of tuple(path, file)'''
    return [(p, file) for p, _, files in os.walk(os.path.abspath(path)) for file in files]


def files_path10(path):
    '''return list of string'''
    return [os.path.join(p, file) for p, _, files in os.walk(os.path.abspath(path)) for file in files]

Listing with pathlib python 3.8.x feature

def files_path11(path):
    p = pathlib.Path(path)
    return list(p.glob(**/*))

5

You can use the the walk., it returns a tuple with the path, directory, file, as you are interested only in the file, can ignore the first two parts, doing:

for _, _, arquivo in os.walk('/home/user'):
    print(arquivo)

1

If your intention is to list only the files of a particular directory you can:

  1. Inform the directory path;
  2. Request the display of the files in this directory.

For this you can use the following code:

from os import chdir, getcwd, listdir
from os.path import isfile

cam = input('Digite o caminho: ')

chdir(cam)
print(getcwd())

for c in listdir():
    if isfile(c):
        print(c)

Now, if you intend to display all the content from a given directory - folders and files - you can:

  1. Inform the directory path;
  2. Request the display of all contents of the respective directory.

For this you can use the following code:

from os import chdir, getcwd, listdir

cam = input('Digite o caminho: ')

chdir(cam)
print(getcwd())

for c in listdir():
    print(c)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.