如何更改文件中的字节?

2024-10-01 09:22:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个加密程序,我需要在二进制模式下打开文件来访问非ascii和不可打印字符,我需要检查文件中的字符是字母、数字、符号还是不可打印字符。这意味着我必须检查字节(当它们被解码为ascii时)是否与以下任何字符匹配:

{^9,dzEV=Q4ciT+/s};fnq3BFh% #2!k7>YSU<GyD\I]|OC_e.W0M~ua-jR5lv1wA`@8t*xr'K"[P)&b:g$p(mX6Ho?JNZL

我想我可以把上面的字符编码成二进制,然后用字节来比较。我不知道怎么做。在

P.S. Sorry for bad English and binary misunderstanding. (I hope you know what I mean by bytes, I mean characters in binary mode like this):

^{pr2}$

Tags: 文件程序字节字母ascii二进制模式符号
2条回答

要以二进制模式打开文件,请使用open("filena.me", "rb")命令。我从来没有亲自使用过这个命令,但这应该能让你得到你需要的信息。在

Python中有两种主要的字符串类型:表示二进制数据的bytestrings(字节序列)和表示人类可读文本的Unicode字符串(Unicode码位序列)。把一个转换成另一个很简单(☯)公司名称:

unicode_text = bytestring.decode(character_encoding)
bytestring = unicode_text.encode(character_encoding)

如果以二进制模式打开文件,例如'rb',则file.read()返回bytestring(bytes类型):

^{pr2}$

有几种方法可用于对字节进行分类:

  • 字符串方法,如bytes.isdigit()

    >>> b'1'.isdigit()
    True
    
  • 字符串常量,如string.printable

    >>> import string
    >>> b'!' in string.printable.encode()
    True
    
  • 正则表达式,如\d

    >>> import re
    >>> bool(re.match(br'\d+$', b'123'))
    True
    
  • curses.ascii模块中的分类函数,例如curses.ascii.isprint()

    >>> from curses import ascii
    >>> bytearray(filter(ascii.isprint, b'123'))
    bytearray(b'123')
    

bytearray是一个可变的字节序列-与bytestring不同,您可以就地更改它,例如,每三个大写字节都要小写:

>>> import string
>>> a = bytearray(b'ABCDEF_')
>>> uppercase = string.ascii_uppercase.encode()
>>> a[::3] = [b | 0b0100000 if b in uppercase else b 
...           for b in a[::3]]
>>> a
bytearray(b'aBCdEF_')

注意:b'ad'是小写的,但是b'_'保持不变。在


要想就地修改二进制文件,可以使用mmap模块,例如,在'file'中每隔一行将第4列小写:

#!/usr/bin/env python3
import mmap
import string

uppercase = string.ascii_uppercase.encode()
ncolumn = 3 # select 4th column
with open('file', 'r+b') as file, \
     mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_WRITE) as mm:
    while True:
        mm.readline()   # ignore every other line
        pos = mm.tell() # remember current position
        if not mm.readline(): # EOF
            break
        if mm[pos + ncolumn] in uppercase:
            mm[pos + ncolumn] |= 0b0100000 # lowercase

注意:python2和3api在本例中有所不同。代码使用python3。在

输入

ABCDE1
FGHIJ
ABCDE
FGHI

输出

ABCDE1
FGHiJ
ABCDE
FGHi

注意:第4列在第2行和第4行变为小写。在


通常,如果要更改文件:读取文件,将修改写入临时文件,成功后将临时文件移到原始文件的位置:

#!/usr/bin/env python3
import os
import string
from tempfile import NamedTemporaryFile

caesar_shift = 3
filename = 'file'

def caesar_bytes(plaintext, shift, alphabet=string.ascii_lowercase.encode()):
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    return plaintext.translate(plaintext.maketrans(alphabet, shifted_alphabet))

dest_dir = os.path.dirname(filename)
chunksize = 1 << 15
with open(filename, 'rb') as file, \
     NamedTemporaryFile('wb', dir=dest_dir, delete=False) as tmp_file:
    while True: # encrypt
        chunk = file.read(chunksize)
        if not chunk: # EOF
            break
        tmp_file.write(caesar_bytes(chunk, caesar_shift))
os.replace(tmp_file.name, filename)

输入

abc
def
ABC
DEF

输出

def
ghi
ABC
DEF

要转换回输出,请设置caesar_shift = -3。在

相关问题 更多 >