删除前6个字节和最后一个字节的最佳方法.Python [英] Best way to remove first 6 bytes, and very last byte. Python

查看:127
本文介绍了删除前6个字节和最后一个字节的最佳方法.Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在寻找获取文件的最佳方法,删除前6个字节和最后一个字节,然后将其另存为.JPG格式.(原始文件是.TEC格式,用作照片的缓存.)

I'm simply looking for the best way to take a file, remove the first 6 bytes, and the very last byte, then save it as a .JPG format. (Original file is a .TEC format, used as Cache for Photos.)

解决了它甚至使它循环到我的文件名"Old(1)""Old(2)"等的地方.以这种方式重命名它们更容易了.因为Windows会自动以这种格式重命名.我有444个文件要转换,并且效果很好.现在,我可以看到所有裸照.赢.

Solved and even made it loop to where my file names where "Old (1)" "Old (2)" etc. It was easier to just rename them all this way. as windows will rename in this format automatically. I had 444 files to convert, and this worked great. Now I get to see all the nudes. Win.

x = 1
while (x < 445):
   fp = open('Change ('+str(x)+').tec', "rb")
   data = fp.read()
   fp.close()

   fp = open('Changed ('+str(x)+').jpg', "wb")
   fp.write(data[6:-1])
   fp.close()
x = x + 1

推荐答案

不确定"best"是什么意思,但最简单的方法可能是全部阅读并切成字符串:

Not sure what you mean by "best", but probably the easiest way is to just read it all in and slice the string:

fp = open(filename, "rb")
data = fp.read()
fp.close()

fp = open(jpegfilename, "wb")
fp.write(data[6:-1])
fp.close()

正如评论中指出的那样,如果您的JPEG很大,那么一次读取整个内容可能会耗尽您的内存.相反,您可以一次阅读一下,就像这样:

As pointed out in the comments, if your JPEG is very large, reading the whole thing at once could exhaust your memory. Instead, you could read it a bit at a time, like this:

with open(filename, "rb") as ifile:
    with open(jpegfilename, "wb") as ofile:
        ifile.read(6)
        prev = None
        while True:
            chunk = ifile.read(4096)
            if chunk:
                if prev:
                    ofile.write(prev)
                prev = chunk
            else:
                break
        if prev:
            ofile.write(prev[:-1])

但是考虑到大多数JPEG可能不会耗尽内存,因此这可能比您真正需要的要复杂得多.

But given that most JPEG's probably aren't going to come anywhere close to exhausting your memory, this is probably way more complicated than you really need.

这篇关于删除前6个字节和最后一个字节的最佳方法.Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆