使用绝对目录而不是更改 cwd

Working with absolute directory instead of changing the cwd

我想通过绝对路径从文件夹中导入一些 csv 文件,而不是更改当前工作目录 (cwd)。然而,这在以下情况下不起作用,除非我更改工作目录。哪一部分不正确?

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'

对于您的情况,最简单的方法是指定基本路径并使用它来操作所有其他路径。

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

或者你可以做一些完全相同的事情:

files = [os.path.join(path, f) for f in os.listdir(path)]
    In [2]: for file in files:
                data=pd.read_csv(file)