Search code examples
pythoncsvabsolute-pathcwd

Working with absolute directory instead of changing the cwd


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'


Solution

  • 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)