python读取视频文件,Python-如何将视频文件读取为二进制数据?

My assignment asks me to compute a hash from a video file. So I'm guessing what I need to do, is to somehow read the video file as binary data, and then do the hashing shenanigans with that. The problem is, I only know how to read from and write to .txt files - video files are completely new to me. So my questions are:

How do I take a file and read it as binary data?

How do I handle this data? I mean, should I just stick it into a string or should I use an array of some sort? I imagine the amount of numbers is going to be huge and I wouldn't like my computer to crash because I handled the data in some horribly inefficient way :D.

Also, I am not entirely sure what I am talking about when I say "binary data", as I have limited experience with that kind of stuff. I mean, it's not just a string of 1s and 0s right?. So I would also appreciate a crash course on "binary data" :D

解决方案

There is really no difference between text data and binary data. A string is just a sequence of bytes. Every byte, or several byte, values corresponds to a text character. Because of this we can read and store binary data (a sequence of bytes) just like a string. The only difference is that the sequence of characters we read from binary will probably not be readable by humans.

Mark the file open format with "rb" (read binary) to avoid text line ending problems.

To handle large files, you could read a small number of bytes at a time and compute the hash of the bytes as you go.

started = 0

hash_val = 0

with open("video", "rb") as file:

byte = file.read(1) # read a byte (a single character in text)

byte_val = ord(byte) # convert the string character into a number

if started == 0:

hash_val = byte_val

started = 1

hash_val = (hash_val << 5) - hash_val + byte_val # this is a basic hash

print(hash_val)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值