get file in folder python code example

Example 1: python list files in current directory

import os

files = os.listdir('.')
print(files)
for file in files:
  # do something

Example 2: python get filename from path

import os
print(os.path.basename(your_path))

Example 3: get files in directory python

import os
files_and_directories = os.listdir("path/to/directory")

Example 4: python read all text files in directory

import os
from re import search

arr = os.listdir()
strtxt = ".txt"
for txtfile in arr:
    if txtfile.__contains__(strtxt):
        fileObject = open(txtfile, "r")
        data = fileObject.read()
        print(data)

Example 5: python get all file names in a dir

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

Example 6: python get files in directory

from pathlib import Path
for txt_path in Path("/path/folder/directory").glob("*.txt"):
  print(txt_path)