使用 os.walk 查找和打印我的文件的名称,但无法打开它们?路径名问题? [英] Using os.walk to find and print names of my files, but unable to open them? Path name issue?

查看:58
本文介绍了使用 os.walk 查找和打印我的文件的名称,但无法打开它们?路径名问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的相关代码块如下:

path = "\\Users\\Harmless\\Documents\\untitled"
cellorder = []
cellcont = []
for roots, dirs, files, in os.walk(path):
    for file in natural_sort(files):
        if "Row" in file:
            cellorder.append(file)
            with open(file,'r') as txt:
                print txt.readlines
            #print "file = %s" % file

这将成功列出我想要打开的所有文件(如注释掉的那样),但是当我尝试以与打印文件名相同的方式传入文件名以读取它时:

This would successfully list all the files I want to open (as commented out), but when I try to pass in the filename the same way it was printed in order to read it:

IOError: [Errno 2] No such file or directory: 'Row0Col0Heat.txt'

我该如何解决这个问题?我是否需要在每个文件名中引用整个路径名和字符串替代?如果是这样,为什么?有没有更好的方法来引用/利用路径?

How can I fix this? Do I need to reference the entire path name and string substitute in each filename? If so, why? Is there a better way to reference/utilize paths?

推荐答案

尝试使用文件的绝对路径,可以通过

Try using the absolute path of the file, you can get the absolute path by

abs_file_path = os.path.abspath(file)

既然你已经有了基本路径,你也可以使用:

since you already have the base path, you can also use:

abs_file_path = os.path.join(path, file)

希望能帮到你

这篇关于使用 os.walk 查找和打印我的文件的名称,但无法打开它们?路径名问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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