英文:
Deleting a line from a Python text file
问题
try:
with open("test.txt", "r") as file:
lines = file.readlines()
except FileNotFoundError:
print("File not found!")
word = "five"
try:
with open("test.txt", "w") as file:
file.writelines(line for line in lines if word not in line)
except FileNotFoundError:
print("File not found!")
英文:
While I was learning how to work with files in Python, I had a question: How can you delete a line from a file that contains a specific word. I wrote the following code:
arr = []
try:
with open("test.txt") as file:
arr = file.readlines()
except FileNotFoundError:
print("File not found!")
word = "five"
try:
with open("test.txt", "w") as file:
for row in arr:
if word not in row:
file.write(row)
except FileNotFoundError:
print("File not found!")
But I would like to know if it is possible to do this without writing all the lines in one array, because the file can sometimes be very large and there can be a lack of memory.
答案1
得分: 0
你只需要执行以下操作:
- 以读写模式打开它。
- 读取并筛选掉行。
- 将光标移动到文件的开头。
- 写回文件。
- 删除除此之外的任何内容。
with open("test.txt", "r+") as f:
output = filter(lambda line: word not in line, f.readlines())
f.seek(0)
f.write(''.join(output))
f.truncate()
为了改善内存使用情况,只需逐行使用 f.readline()
读取文件,并根据需要动态调整 seek 位置。
with open("test.txt", "r+") as f:
latest_written_position = f.tell()
line = f.readline()
reading_position = f.tell()
while line:
if word not in line:
f.seek(latest_written_position)
f.write(line)
latest_written_position = f.tell()
f.seek(reading_position)
line = f.readline()
reading_position = f.tell()
f.seek(latest_written_position)
f.truncate()
英文:
You just need to do the following:
> 1. open it in read and write mode.
> 2. Read it and filter the line out
> 3. move the cursor to the begin of the file
> 4. write it back
> 5. remove anything than is after it
with open("test.txt", "r+") as f:
output = filter(lambda line: word not in line, f.readlines())
f.seek(0)
f.write(''.join(output))
f.truncate()
To improve memory usage, just read the file line by line using f.readline() and adjust the seek dinamically.
with open("test.txt", "r+") as f:
latest_written_position = f.tell()
line = f.readline()
reading_position = f.tell()
while line:
if word not in line:
f.seek(latest_written_position)
f.write(line)
latest_written_position = f.tell()
f.seek(reading_position)
line = f.readline()
reading_position = f.tell()
f.seek(latest_written_position)
f.truncate()
答案2
得分: -1
这应该能奏效:
try:
with open("test.txt") as file:
arr = file.readlines()
except IOError:
from sys import exit as exit_the_program
try:
exit_the_program(__status=-1)
except:
import sys
exiter = sys
del sys
exiter.exit()
finally:
try:
condition = True
arr = ['hello', 'world'] ## or comment?
local_i = len(arr)
for i, elem in enumerate(reversed(arr), start=1):
local_i -= i
if condition: # example
del i
if not local_i:
del local_i
del elem
del arr[local_i]
print(arr)
with open('out_f.xtxt', 'w') as of:
of.write(arr)
except Exception as __this_thing_went_wrong:
print(__this_thing_went_wrong)
from sys import exit as exit_the_program
success = 123
exit_the_program(~success)
英文:
This should do the trick:
try:
with open("test.txt") as file:
arr = file.readlines()
except IOError:
from sys import exit as exit_the_progrem
try:
exit_the_progrem(__status=-1)
except:
import sys
exiter = sys
del sys
exiter.exit()
finally:
try:
condtion = True
arr = ['hello', 'world'] ## or comment?
locl_i = len(arr)
for i, elem in enumerate(reversed(arr), start=1):
locl_i -= i
if condtion: # example
del i
if not locl_i:
del locl_i
del elem
del arr[locl_i]
print(arr)
with open('out_f.xtxt', 'w') as of:
of.write(arr)
except Exception as __this_thing_went_wrong:
print(__this_thing_went_wrong)
from sys import exit as exit_the_progrem
success = 123
exit_the_progrem(~success)
答案3
得分: -2
你可以按照阅读的方式写,而不是存储
考虑以下内容:
try:
with open("test.txt") as file:
with open("new_test.txt", "w") as new_file:
for row in file:
if word not in row:
new_file.write(row)
except FileNotFoundError:
print("File not found!")
英文:
You can write as you read instead of storing
Consider the following:
try:
with open("test.txt") as file:
with open("new_test.txt", "w") as new_file:
for row in file:
if word not in row:
new_file.write(row)
except FileNotFoundError:
print("File not found!")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论