python - 如何从文件夹内的 n 个 csv 文件导入数据?

标签 python csv for-loop if-statement directory

[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/

相关文章:

python - 如何清除Python中的异常状态

ruby - Ruby 中的数据拆分

python-3.x - 在 python 中将 pandas.core.frame.DataFrame 转换为 pandas 数据帧

csv - 按列名解析 Athena 中的 CSV

java - 用叠瓦式 for 循环填充数组

windows - 批处理文件: GOTO in a FOR loop

python - selenium 通过 xpath 查找元素出现错误,其中 lxml 中的相同表达式可以

python - sys.stdout.encoding、locale.getpreferredencoding() 和 sys.getdefaultencoding() 之间有什么区别?

python - 我已经为 GCSE Computing 创建了一个食谱程序,但我缺少一个步骤

Swift - 如何在一群人之间平均分配一笔钱?