[Python 帮助]
您好,我需要一些帮助来了解如何从文件夹内的 n 个文件导入数据。当我尝试提取实际数据时,出现错误,指出文件/目录不存在。
import os, csv
path = ("my directory")
files = sorted(os.listdir(path))
def f():
for file in (files):
with open(file, 'r') as csvfile:
data = csvfile.read
print(data)
OUTPUT:
File "<ipython-input-158-1f4c11da5a68>", line 1, in <module>
f()
File "<ipython-input-157-b977510dbfcd>", line 8, in f
with open(file, 'r') as csvfile:
FileNotFoundError: [Errno 2] No such file or directory: '.csv'
最佳答案
os.listdir
仅返回文件名,不返回路径名,因此打开文件时需要将路径名与文件名连接起来。
更改:
with open(file, 'r') as csvfile:
至:
with open(os.path.join(fcm_path, file), 'r') as csvfile:
关于python - 如何从文件夹内的 n 个 csv 文件导入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59097306/