IOError: [Errno 2] 没有这样的文件或目录试图打开文件 [英] IOError: [Errno 2] No such file or directory trying to open a file

查看:45
本文介绍了IOError: [Errno 2] 没有这样的文件或目录试图打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 非常陌生,所以请原谅下面的基本代码和问题,但我一直在试图找出导致错误的原因(我什至在 SO 上看过类似的线程)但不能解决我的问题.

I am very new to Python so please forgive the following basic code and problem, but I have been trying to figure out what is causing the error I am getting (I have even looked at similar threads on S.O.) but can't get past my issue.

这是我想要做的:

  • 遍历一个包含 CSV 文件的文件夹
  • 搜索关键字"并删除包含关键字"的所有行
  • 将输出保存到单独的文件夹

这是我的代码:

import os, fnmatch
import shutil

src_dir = "C:/temp/CSV"
target_dir = "C:/temp/output2"
keyword = "KEYWORD"

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)
    with open(f):
        for line in f:
            if keyword not in line:
                write(line)
                shutil.copy2(os.path.join(src_dir, f), target_dir)

这是我得到的错误:

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

我已经确认文件夹和文件确实存在.是什么导致了 IOError 以及如何解决它?另外,我的代码是否还有其他错误会阻止我执行整个任务?

I have confirmed that the folder and file do exist. What is causing the IOError and how to I resolve it? Also, is there anything else wrong with my code that would prevent me from performing the entire task?

推荐答案

嗯,这里出了一些问题.

Hmm, there are a few things going wrong here.

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)

您没有存储 join 的结果.这应该是这样的:

You're not storing the result of join. This should be something like:

for f in os.listdir(src_dir):
    f = os.path.join(src_dir, f)

这个公开调用是您的 IOError 的原因.(因为没有存储上面 join 的结果,f 仍然只是 'file.csv',而不是 'src_dir/file.csv'.)

This open call is is the cause of your IOError. (Because without storing the result of the join above, f was still just 'file.csv', not 'src_dir/file.csv'.)

另外,语法:

with open(f): 

很接近,但语法不太正确.它应该是 with open(file_name) as file_object:.然后,您使用 file_object 来执行读或写操作.

is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:. Then, you use to the file_object to perform read or write operations.

最后:

write(line)

你告诉 python 你想写什么,但没有告诉 Python 在哪里写它.Write 是文件对象上的一个方法.试试 file_object.write(line).

You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line).

编辑:您也在破坏您的输入文件.您可能想要打开 输出文件并在从输入文件中读取它们时向其中写入行.

Edit: You're also clobbering your input file. You probably want to open the output file and write lines to it as you're reading them in from the input file.

参见:python中的输入/输出.

这篇关于IOError: [Errno 2] 没有这样的文件或目录试图打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆