Answers for "list file in folder python"

18

python list files in current directory

import os

files = os.listdir('.')
print(files)
for file in files:
  # do something
Posted by: Guest on November-04-2020
7

list files in directory python

import os
print(os.listdir('/path/to/folder/to/list'))
Posted by: Guest on April-22-2020
1

python list all files in directory

import os
 arr = os.listdir()
 print(arr)
 
 >>> ['$RECYCLE.BIN', 'work.txt', '3ebooks.txt', 'documents']
Posted by: Guest on April-15-2021
8

python script to read all file names in a folder

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")
Posted by: Guest on March-26-2020
1

get the list of file names from a folder in python

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

# Getting file path from user and store it on path variable
path = input("Please enter a directory name:\n")

# Try catch for printing error message if the user enter invalid path
try:
    # Getting list of file from the given path and store it in (onlyfiles) variable
  onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]

    # Looping through the file and print each file
  for file in onlyfiles:
    print(file)

except Exception as e:
    # If there is some error, print error message
  print("Incorrect path.")
Posted by: Guest on September-29-2021

Python Answers by Framework

Browse Popular Code Answers by Language