0

I would like to import some csv files from a folder by means of an absolute path rather than changing the current working directory (cwd). Nevertheless, this doesn't work in the following case, unless I change the working directory. Which part is incorrect?

In [1]: path = r"C:\Users\ardal\Desktop\Exported csv from single cell"
        files = os.listdir(path)
        files

Out [1]: ['210403_Control_Integer.csv',
 '210403_Vert_High_Integer.csv',
 '210403_Vert_Low_Integer.csv',
 '210403_Vert_Medium_Integer.csv']

In [2]: for file in files:
            data=pd.read_csv(file)

Out [2]: 

FileNotFoundError: [Errno 2] No such file or directory: '210403_Control_Integer.csv'

Ardalan1
  • 99
  • 7
  • 1
    When iterating over the result of `os.listdir` the filenames do not include the path - you need to prepend that yourself. Printing `file` in your loop would demonstrate this, as does the error message which doesn't include the path. – Kemp Jul 26 '21 at 09:30
  • @Kemp I see your point. In other words, I had to pay attention to the outcome of "files" instead of focusing on the "path". Thanks! – Ardalan1 Jul 26 '21 at 09:45

1 Answers1

0

In your case, the simplest way to do it is to specify the base path and use that to manipulate all other paths.

path = 'C:/Users/ardal/Desktop/Exported csv from single cell'
files = os.listdir(path)
In [2]: for file in files:
            data=pd.read_csv(os.path.join(path, file))

Or you can do something like this which is exactly the same:

files = [os.path.join(path, f) for f in os.listdir(path)]
    In [2]: for file in files:
                data=pd.read_csv(file)
azal
  • 1,210
  • 6
  • 23
  • 43