python read files in directory code example

Example 1: python get all file names in directory

import glob
print(glob.glob("/home/adam/*.txt"))

Example 2: get files in directory python

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

Example 3: 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 4: python find file in directory

# option A (i think this is faster, not in micropython)

import os

if os.path.isfile("test.dat"):
	print("yes") #file found
else:
	print("no") #file not found

# also this is posible
# from os.path import isfile
# if isfile("test.dat"):


# option B (posible in micropython)

import os

if "test.dat" in os.listdir():
	print("yes") # file found
else:
	print("no") # file not found

# os.lisdir() return a array whit all the files found in the directory

Example 5: open file in python directory

path = 'C:\\Users\\Username\\Path\\To\\File'
file=open(path, "r")

Example 6: how to make all my files to work together in python

>>> import os
>>> entries = os.listdir('my_directory/')