me=1
while (me < 244):
f=open('%s' % me, 'rb')
tdata = f.read()
f.close()
ss = '\xff\xd8'
se = '\xff\xd9'
count = 0
start = 0
while True:
x1 = tdata.find(ss,start)
if x1 < 0:
break
x2 = tdata.find(se,x1)
jpg = tdata[x1:x2+1]
count += 1
fname = 'extracted%d03.jpg' % (count)
fw = open(fname,'wb')
fw.write(jpg)
fw.close()
start = x2+2
me=me+1
我正在尝试为多个文件运行它。 但它只会忽略文件1和其他文件的操作。 我是python的新手,任何人都可以稍微调整一下吗?
答案 0 :(得分:1)
在最后一行代码中,您要在嵌套的while循环中递增me
,以便为每个文件运行。要解决此问题,只需取消缩进me
即可。
#!/usr/bin/python
me=1
while (me < 244):
f=open('%s' % me, 'rb')
tdata = f.read()
f.close()
ss = '\xff\xd8'
se = '\xff\xd9'
count = 0
start = 0
while True:
x1 = tdata.find(ss,start)
if x1 < 0:
break
x2 = tdata.find(se,x1)
jpg = tdata[x1:x2+1]
count += 1
fname = 'extracted%d03.jpg' % (count)
fw = open(fname,'wb')
fw.write(jpg)
fw.close()
start = x2+2
me=me+1 # this needs to be outside of your nested while loop
话虽如此,您可能希望改进此代码中变量的名称(使它们更具描述性!),将while循环中的代码提取到函数中也可能是个好主意。还值得一提的是,外部while循环可以(并且应该)替换为for循环。
这样的事情:
def do_something_with_file(me):
f=open('%s' % me, 'rb')
tdata = f.read()
f.close()
ss = '\xff\xd8'
se = '\xff\xd9'
count = 0
start = 0
while True:
x1 = tdata.find(ss,start)
if x1 < 0:
break
x2 = tdata.find(se,x1)
jpg = tdata[x1:x2+1]
count += 1
fname = 'extracted%d03.jpg' % (count)
fw = open(fname,'wb')
fw.write(jpg)
fw.close()
start = x2+2
for i in range(1, 244):
do_something_with_file(i)