有人帮我修复IOError?

时间:2017-03-16 04:18:20

标签: python csv

这是尝试更新内容的功能:

def write_csv(self, file_path, fields, rows):
    with open(file_path, 'wb') as csvFile:
        writer = csv.DictWriter(csvFile, fieldnames=fields)
        writer.writerow(dict(zip(fields, fields)))
        for row in rows:
            writer.writerow(row)

我得到的错误如下:

C:\sample_data_set.csv
Initial Records : 19
Removed : 3
Traceback (most recent call last):
File "C:/Python_project/amit_test.py", line 79, in <module>
v.main()
File "C:/Python_project/amit_test.py", line 73, in main
self.write_csv('output/{0}'.format(os.path.basename(file_path)), fields,      rows)
File "C:/Python_project/amit_test.py", line 41, in write_csv
with open(file_path, 'wb') as csvFile:
IOError: [Errno 2] No such file or directory: 'output/sample_data_set.csv'

我已经检查过sample_data_set.csv的路径是否正确并且确实存在。

此处提供完整代码https://gist.github.com/shashank136/f5557a1d0a42d1ae615a6e4c12b21ff7

2 个答案:

答案 0 :(得分:0)

FILE_PATH

也许

file_path = r"C:\Python_project\output\sample_data_set.csv"

你可以尝试!

答案 1 :(得分:0)

取决于你的file_path,注意它在你打开文件时没有自动创建中间目录

import os

def write_csv(self, file_path, fields, rows):

    os.makedirs(os.path.dirname(file_path), exist_ok=True)

    with open(file_path, 'wb') as csvFile:
        writer = csv.DictWriter(csvFile, fieldnames=fields)
        writer.writerow(dict(zip(fields, fields)))
        for row in rows:
            writer.writerow(row)