开发者

how to correct this in python 3.0

开发者 https://www.devze.com 2023-03-30 02:57 出处:网络
I am a newer to python. After I leraned some basic in python, I try to write some program by imitating other\'s.

I am a newer to python. After I leraned some basic in python, I try to write some program by imitating other's. And I find some code in python2.0 and it can't work in 3.0. How can I fix it.

import sys
import开发者_StackOverflow社区 os
import string

headers = [ ('JFIF', 6, 'jpg'), ('GIF', 0, 'gif'), ('PNG', 1, 'png') ] 
marker = []
fileName = r'd:\\first.doc'

try:
    fid = open(fileName, 'rb')   #open file in binary mode not text mode
except:
    print("can't open file",fileName)
    sys.exit(1)

s = 0
for line in fid:
    for flag, offset, ext in headers:
        index = string.find(line, flag)  #error occurs here. 
        if index > 0 :
            pos = s + index - offset
            marker.append((pos, ext))
        s += len(line)

------------------------after edit------------------------------------- The purpose of this code is to save pictures in the documents like doc,pdf. And this is the first step, which is to find the pictures' header in the file

I would try the following correction,but failed index = string.find(line, flag) -> index = line.find(flag)

index = string.find(line, flag) -> index = str.find(line,flag)


change

headers = [ ('JFIF', 6, 'jpg'), ('GIF', 0, 'gif'), ('PNG', 1, 'png') ] 
...
string.find(line, flag)

to

headers = [ (b'JFIF', 6, 'jpg'), (b'GIF', 0, 'gif'), (b'PNG', 1, 'png') ] 
...
line.find(flag)

the string. change is really just moving the call to the object rather than using a library.

the b'' change is more interesting. python 3 is more careful with the difference between strings and bytes. because you opened your file in binary mode it is returning bytes. so you need to check what is returned against bytes, rather than against strings.

0

精彩评论

暂无评论...
验证码 换一张
取 消