使用Python中的文件操作删除文本

huangapple go评论59阅读模式
英文:

Delete text using file operators in python

问题

你可以使用以下代码将文件 "example.pdf" 中第一个 "Hello" 之后的内容删除:

with open("example.pdf", "r+") as file:
    data = file.read()
    index = data.find("Hello")
    if index != -1:
        file.seek(index)
        file.truncate()

这段代码将文件 "example.pdf" 中第一个 "Hello" 之后的内容截断,使其被删除。

英文:

Say there is a code:

with open("example.pdf", "r") as file:
  String = file.seek(-11, os.SEEK_END)
  print(String)

and the output is Hello Hello

How would you change the text in the file "example.pdf" so that everything after the first Hello is deleted using file operators(read/write/append)?

Thank you for your help!!

答案1

得分: 2

打开文件以适当的模式。确定要截断文件的偏移量。调用truncate()并关闭文件。

例如(对于普通文本文件):

import os

def remove_after(filename, text):
    with open(filename, 'r+') as f:
        contents = f.read()
        offset = contents.find(text)
        if offset >= 0:
            pos = offset + len(text)
            f.seek(pos, os.SEEK_SET)
            f.truncate()

remove_after('/Volumes/G-Drive/foo.txt', 'hello')

对于二进制文件,模式应为'rb+',确定截断点的机制可能会有所不同。

请注意,从二进制文件中删除任意内容可能会破坏其内部结构,具体取决于文件的内容。

英文:

Open the file in the appropriate mode. Determine the offset where you want to truncate the file. Call truncate() and close the file.

For example (for a plain text file):

import os

def remove_after(filename, text):
    with open(filename, 'r+') as f:
        contents = f.read()
        offset = contents.find(text)
        if offset >= 0:
            pos = offset + len(text)
            f.seek(pos, os.SEEK_SET)
            f.truncate()

remove_after('/Volumes/G-Drive/foo.txt', 'hello')

For a binary file the mode should be rb+ and the mechanism for determining the truncation point is likely to be different.

Bear in mind though that deleting arbitrary content from a binary file may break its internal structure depending on what the file is

huangapple
  • 本文由 发表于 2023年6月19日 15:47:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定