简体   繁体   中英

Python: .png image file that wont open because of text before file signature

I have a large series of png files that have had some text added before the ‰PNG file signature. I'm trying to find a way of opening the files in python and deleting the extra text before writing to a new file, so I can view the images.

A screenshot from Notepad++ of the file can be seen in the below image to give a better understanding of the problem.

first few lines of file showing additional text before file signature

So far I have tried this code

infile = open('radar0.1.107652907', encoding='ANSI')
outfile = open('test.png', 'w', encoding='ANSI')

imagetext = infile.read()

pos = imagetext.find('‰')

outtext = imagetext[pos:]

outfile.write(imagetext)

But when I try and open the new file it wont open.

Any help would be massively appreciated

I was able to solve the issue using @BoarGules suggestion to work in binary. Code is below

infile = open('radar0.1.107652907', 'rb')
outfile = open('test.png', 'wb')

imagetext = infile.read()

pos = imagetext.find(b'\x89PNG')

outtext = imagetext[pos:]

outfile.write(outtext)


infile.close()
outfile.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM