在python中使用os.walk更改目录

时间:2012-12-04 18:14:12

标签: python recursion ioerror os.walk

我正在尝试编写一些递归搜索路径和子目录的文件,这些文件以十六进制值“FFD8”开头。在运行脚本时,我已经使用它来处理参数参数中指定的位置,但是当它需要移动到子目录时会出现问题。

import string, sys, os
 os.chdir(sys.argv[1])
 for root, dir, files in os.walk(str(sys.argv[1])):
         for fp in files:
             f = open(fp, 'rb')
             data = f.read(2)
             if "ffd8" in data.encode('hex'):
                 print "%s starts with the offset %s" % (fp, data.encode('hex'))
             else:
                 print "%s starts wit ha different offset" % (fp)

我不知道为什么我需要使用os.chdir命令但由于某些原因没有它,当从我的桌面运行脚本时它会忽略参数并始终尝试从桌面目录运行搜索,无论如何我指定的路径。

此输出为autodl2.cfg starts wit ha different offset DATASS.jpg starts with the offset ffd8 IMG_0958.JPG starts with the offset ffd8 IMG_0963.JPG starts with the offset ffd8 IMG_0963_COPY.jpg starts with the offset ffd8 project.py starts wit ha different offset Uplay.lnk starts wit ha different offset Traceback (most recent call last): File "C:\Users\Frosty\Desktop\EXIF PROJECT\project2.py", line 15, in <module> f = open(fp, 'rb') IOError: [Errno 2] No such file or directory: 'doc.kml'

现在我知道为什么它出错的原因,这是因为文件doc.kml位于桌面上的子文件夹中。任何人都可以轻松地更改目录的最简单方法,以便它可以继续扫描子目录没有问题吗?谢谢!

1 个答案:

答案 0 :(得分:4)

您需要使用绝对文件路径来打开它们,但files仅列出没有路径的文件名。但是,root变量确实包含当前目录的路径。

使用os.path.join加入两者:

for root, dir, files in os.walk(str(sys.argv[1])):
    for fp in files:
        f = open(os.path.join(root, fp), 'rb')