问题描述
我想通过绝对路径而不是更改当前工作目录 (cwd) 从文件夹导入一些 csv 文件。尽管如此,这在以下情况下不起作用,除非我更改工作目录。哪个部分不正确?
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)