我试图编写一些递归搜索路径和子目录中以“FFD8”十六进制值开头的文件。在运行脚本时,我已经将它与参数参数中指定的位置一起使用,但是当它需要移动到子目录时会出现问题。在python中使用os.walk更改目录
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是桌面上的一个子文件夹内。任何人都可以通过最简单的方式来改变目录,以便它可以继续扫描子目录而不会出现问题吗?谢谢!
小细节:这将是较好的去除行'数据= f.read(2)',取而代之的if语句'如果f.read (2)=='\ xff \ xd8':'。它实际上是相同的,只是它不执行十六进制编码的事情。 – Robin