Why does pd.read_sas() work for individual files but not when iterating through a folder?

137 views Asked by At

I'm attempting to iterate over some SAS files and convert them to a csv. I keep getting a "FileNotFoundError: [Errno 2] No such file or directory: 'table_name.sas7bdat' " error.

import os 
import pandas as pd

files = r"\\path\to\sas\tables"

for file in os.listdir(files):
    if file.endswith(".sas7bdat"):
        sasfile = pd.read_sas(file)
        df = pd.DataFrame(sasfile)
        filepath = r"\\path\to\csv\tables\{}.csv".format(sasfile)
        df.to_csv(filepath)

The file does exist, so I don't know what to do with this error.

I've used both my mapped letter drives and my UNC paths. I've also just run the pd.read_sas() with the individual file and that works fine.

1

There are 1 answers

0
Pepe On

It doesn't work because you are trying to read table_name.sas7bdat instead of \\path\to\sas\tables\table_name.sas7bdat. Change the line sasfile = pd.read_sas(file) for sasfile = pd.read_sas(files+'\'+file) to concatenate the path with the file name. That should solve your problem.