我是否需要将另一个目录中文件的完整路径传递给open()? [英] Do I need to pass the full path of a file in another directory to open()?

查看:100
本文介绍了我是否需要将另一个目录中文件的完整路径传递给open()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要循环浏览的文件夹,其中有十个文件.当我打印出文件名时,我的代码可以正常工作:

I have a folder with ten files in it which I want to loop through. When I print out the name of the file my code works fine:

import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)

哪些印刷品:

1
2
3
4
5
6
7
8
9
10

但是,如果我尝试在循环中打开文件,则会出现IO错误:

But if I try to open the file in the loop I get an IO error:

import os
indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        log = open(f, 'r')

Traceback (most recent call last):
File "/home/des/my_python_progs/loop_over_dir.py", line 6, in <module>
log = open(f, 'r')
IOError: [Errno 2] No such file or directory: '1'
>>> 

即使在循环内我也需要将文件的完整路径传递给open()吗?

Do I need to pass the full path of the file even inside the loop to open() them?

推荐答案

是的,您需要完整路径.

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

是快速解决方案.正如注释所指出的那样,os.walk会下降到子目录中,因此您确实需要使用当前目录的根目录,而不是使用indir作为路径联接的基础.

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

这篇关于我是否需要将另一个目录中文件的完整路径传递给open()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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