【问题标题】:Python: [Errno 2] No such file or directoryPython:[Errno 2] 没有这样的文件或目录
【发布时间】:2016-09-23 17:55:38
【问题描述】:

我想打开并读取特定文件夹中的所有 csv 文件。 我在 OS X El Capitan 版本 10.11.6 上,我使用的是 Python 2.7.10。 我在 phyton 文件中有以下功能:

def open_csv_files(dir):
for root,dirs,files in os.walk(dir):
    for file in files:
        if file.endswith(".csv"):
            f= open(file)
            print "FILE OPEN, AND DO SOMETHING... "
            f.close
return

我打电话给open_csv_file(./dati/esempi)

这个过程返回

IOError: [Errno 2] No such file or directory: 'sensorfile_1.csv'

我尝试使用绝对路径/Users/Claudia/Desktop/Thesis/dati/esempi/ 调用该过程,但我遇到了同样的错误。

此外,我定义了另一个打印文件夹中所有文件名的程序,该程序正确打印文件夹中的所有文件名。

感谢您的帮助。

【问题讨论】:

  • 当您使用绝对路径/Users/Claudia/Desktop/Thesis/dati/esempi/ 执行f= open(file) 时会发生什么

标签: python-2.7


【解决方案1】:

您需要根据root(基本目录)和文件名的值构建文件的绝对路径。

import os


def open_csv_files(directory):
    for root, dirs, files in os.walk(directory):
        for file_name in files:
            if file_name.endswith(".csv"):
                full_file_path = os.path.join(root, file_name)
                with open(full_file_path) as fh:
                    print "Do something with", full_file_path

【讨论】:

    猜你喜欢
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多