Python在读取文件后删除文件中的行 [英] Python delete row in file after reading it
问题描述
我使用 python 2.7 我正在 while 循环中从文件中读取数据.当我成功读取行时,我想从文件中删除这一行,但我不知道该怎么做 - 有效的方法,所以我不会浪费太多 CPU.
I python 2.7 I am reading data from file in while loop. When I successfully read row, I would like to delete this row from a file, but I dont know how to do it - Efficient way so i dont waste to much of CPU.
read = open("data.csv", 'r')
for row in read:
#code......
if send == True:
-->delete sent line from file, and continue to loop
推荐答案
在进行磁盘 IO 时,您不应该担心 CPU 使用率 -- 与几乎所有内存/CPU 操作相比,磁盘 IO 非常慢.
You shouldn't concern yourself about cpu usage when doing disk IO -- disk IO is very slow compared to almost any in-memory/cpu operation.
从文件中间删除有两种策略:
There are two strategies to deleting from the middle of a file:
将所有要保留的行写入一个辅助文件,然后将辅助文件重命名为原始文件名.
writing all lines to keep to a secondary file, then renaming the secondary file to the original file name.
将文件的其余部分(尾部)复制到要删除的行的开头,然后从文件末尾截断 x
个字节(其中 x
等于要删除的行的长度.
copy the rest (tail) of the file to the beginning of the line you want to delete and then truncating x
bytes off the end of the file (where x
is equal to the length of the line you want to remove.
通常首选数字 1,因为它更容易并且不需要任何锁定.
Number 1 is usually preferred since it is easier and doesn't require any locking.
Mayank Porwal 为您提供了大部分策略 #1.以下是您将如何实施策略 #2:
Mayank Porwal has given you most of strategy #1. Here is how you would implement strategy #2:
# open the file for both reading and writing in binary mode ('rb+')
with open('rmline.txt', 'rb+') as fp:
while 1:
pos = fp.tell() # remember the starting position of the next line to read
line = fp.readline()
if not line:
break # we reached the end of the file
if should_line_be_skipped(line): # only you know what to skip :-)
rest = fp.read() # read the rest of the file
fp.seek(pos) # go to the start position of the line to remove
fp.write(rest) # write the rest of the file over the line to be removed
fp.truncate() # truncates at current position (end of file - len(line))
fp.seek(pos) # return to where the next line is after deletion so we can continue the while loop
这篇关于Python在读取文件后删除文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!