IOError:[Errno 2]没有尝试打开文件的文件或目录

Kei*_*ith 22 python

我是Python的新手,所以请原谅以下基本代码和问题,但我一直在试图找出导致我得到的错误的原因(我甚至在SO上看过类似的线程)但是无法通过我的问题.

这是我想要做的:

  • 循环遍历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)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

IOError: [Errno 2] No such file or directory: 'POS_03217_20120309_153244.csv'
Run Code Online (Sandbox Code Playgroud)

我已确认文件夹和文件确实存在.是什么导致IOError我和如何解决它?另外,我的代码还有什么问题会妨碍我执行整个任务吗?

Set*_*eth 20

嗯,这里有一些问题.

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)
Run Code Online (Sandbox Code Playgroud)

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

for f in os.listdir(src_dir):
    f = os.path.join(src_dir, f)
Run Code Online (Sandbox Code Playgroud)

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

另外,语法:

with open(f): 
Run Code Online (Sandbox Code Playgroud)

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

最后:

write(line)
Run Code Online (Sandbox Code Playgroud)

你告诉蟒蛇什么你想写,但不是在那里写.Write是文件对象上的一种方法.试试file_object.write(line).

编辑:你也在破坏你的输入文件.open当您从输入文件中读取输出文件时,您可能想要输出文件并向其写入行.

请参阅:python中的输入/输出.


jdi*_*jdi 11

尽管@Ignacio为您提供了一个直截了当的解决方案,但我想我可能会添加一个答案,为您提供有关代码问题的更多详细信息...

# You are not saving this result into a variable to reuse
os.path.join(src_dir, f)
# Should be
src_path = os.path.join(src_dir, f)

# you open the file but you dont again use a variable to reference
with open(f)
# should be
with open(src_path) as fh

# this is actually just looping over each character 
# in each result of your os.listdir
for line in f
# you should loop over lines in the open file handle
for line in fh

# write? Is this a method you wrote because its not a python builtin function
write(line)
# write to the file
fh.write(line)
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 5

嗯...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:
Run Code Online (Sandbox Code Playgroud)

此外,您永远不会输出到新文件.


Kei*_*ith 5

仅供参考,这是我的工作代码:

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

for f in os.listdir(src_dir):
    file_name = os.path.join(src_dir, f)
    out_file = os.path.join(target_dir, f)
    with open(file_name, "r+") as fi, open(out_file, "w") as fo:
        for line in fi:
            if keyword not in line:
                fo.write(line)
Run Code Online (Sandbox Code Playgroud)

再次感谢大家的所有好评!