Search code examples
pythonpython-3.xlistdir

How to avoid a FileNotFoundError with os.listdir


I'm developing a loop where each csv in a specified directory is re-sampled and then exported into a new file. I'm getting a FileNotFoundError despite trying with various folders and using exact folder paths.

# Specify folder name
serial = '015'

# Specify directory (note - '...' substitute for the full path used back to the drive letter)

root_dir = '...\\CleanTemps\\{}\\'.format(str(serial)) 

#loop
for filename in os.listdir(root_dir):
    if filename.endswith('.csv'):

        print(filename)

        # Pull in the file
        df = pd.read_csv(filename)

This prints a list of the eight files .csv files in that folder. However, when using the following code to pull in the file (one-by-one as a df to modify, I receive the FileNotFoundError:


#loop
for filename in os.listdir(root_dir):
    if filename.endswith('.csv'):

        # Pull in the file
        df = pd.read_csv(filename)

Solution

  • The path to your file is compose from root_path + your file name, you can use :

    from pathlib import Path 
    
    root_path = Path(root_dir)
    
    for filename in os.listdir(root_path):
        if filename.endswith('.csv'):
    
            # Pull in the file
            df = pd.read_csv(root_path/filename)
    

    or you can use:

    for filepath in root_path.glob("*.csv"):
        df = pd.read_csv(filepath)