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

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

Delete text using file operators in python

问题

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

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

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

英文:

Say there is a code:

  1. with open("example.pdf", "r") as file:
  2. String = file.seek(-11, os.SEEK_END)
  3. 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()并关闭文件。

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

  1. import os
  2. def remove_after(filename, text):
  3. with open(filename, 'r+') as f:
  4. contents = f.read()
  5. offset = contents.find(text)
  6. if offset >= 0:
  7. pos = offset + len(text)
  8. f.seek(pos, os.SEEK_SET)
  9. f.truncate()
  10. 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):

  1. import os
  2. def remove_after(filename, text):
  3. with open(filename, 'r+') as f:
  4. contents = f.read()
  5. offset = contents.find(text)
  6. if offset >= 0:
  7. pos = offset + len(text)
  8. f.seek(pos, os.SEEK_SET)
  9. f.truncate()
  10. 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:

确定