如何在python文件中删除一定数量的字节

2024-09-29 21:28:42 发布

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

我有一个file.txt,其中包含文本12345(总共5个字节)。 我想删除3并将45左移一个字节,总共我想有1245(总共4个字节)

这是我的密码:

with open ('a.txt', "r+b") as fl:
    fl.seek(0)
    onetwo = fl.read(2)
    fl.seek(3)
    fourfive = fl.read(2)
    fl.seek(0)
    fl.write(onetwo+fourfive)

但结果我得到了这样的结论: 12455

我试图截断,但截断无助于解决我正在处理的文件(不是此文件)


Tags: 文件文本txt密码read字节aswith
3条回答

您必须编写一个新文件:

with open ('a.txt', 'r') as f1, open ('b.txt', 'w') as f2:
  # read and write operations...

然后移动文件以覆盖:

import os
os.rename('b.txt', 'a.txt') 

移位字节后,使用truncate方法收缩文件

# Create the original file
with open('foo', 'wb') as f:
    f.write(b'12345')

# Shift the last two bytes, then truncate.
with open('foo', 'r+b') as f:
    f.seek(3)
    d = f.read()   # d == b'45'
    f.seek(2)
    f.write(d)  # overwrites the original 3 and 4 => b'12455'
    f.truncate()  # Shrink to the current position => b'1245'

实际上,您可能不会使用硬编码的偏移量,但这证明了这一点

您需要重写文件,但无法以您尝试的方式完成。我试过这个,它成功了:

with open ('a.txt', "r") as fl:
    fl.seek(0)
    onetwo = fl.read(2)
    fl.seek(3)
    fourfive = fl.read(2)

with open('a.txt','w') as fl:
    fl.write(onetwo+fourfive)

相关问题 更多 >

    热门问题