英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论