如何使用python中的行号从文本文件中删除一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17747522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete a line from a text file using the line number in python
提问by derpyherp
here is an example text file
这是一个示例文本文件
the bird flew
the dog barked
the cat meowed
here is my code to find the line number of the phrase i want to delete
这是我的代码,用于查找我要删除的短语的行号
phrase = 'the dog barked'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if phrase in line:
print 'found at line:', num
what can i add to this to be able to delete the line number (num) i have tried
我可以添加什么才能删除我尝试过的行号(num)
lines = myFile.readlines()
del line[num]
but this doesnt work how should i approach this?
但这不起作用我应该如何解决这个问题?
采纳答案by Jon Clements
You could use the fileinput
module to update the file - note this will remove alllines containing the phrase:
您可以使用该fileinput
模块来更新文件 - 请注意,这将删除包含该短语的所有行:
import fileinput
for line in fileinput.input(filename, inplace=True):
if phrase in line:
continue
print(line, end='')
回答by Martijn Pieters
You start counting at one, but python indices are always zero-based.
您从1开始计数,但 Python 索引始终从零开始。
Start your line count at zero:
从零开始您的行数:
for num, line in enumerate(myFile): # default is to start at 0
or subtract one from num
, deleting from lines
(not line
):
或从 中减去一个num
,从lines
(不line
)中删除:
del lines[num - 1]
Note that in order for your .readlines()
call to return any lines, you need to either re-open the file first, or seek to the start:
请注意,为了让您的.readlines()
调用返回任何行,您需要先重新打开文件,或者寻找开头:
myFile.seek(0)
回答by HKImpact
A user by the name of gnibbler posted something similar to this on another thread.
一位名叫 gnibbler 的用户在另一个线程上发布了类似的内容。
Modify the file in place, offending line is replaced with spaces so the remainder of the file does not need to be shuffled around on disk. You can also "fix" the line in place if the fix is not longer than the line you are replacing
就地修改文件,有问题的行被替换为空格,因此文件的其余部分不需要在磁盘上随意移动。如果修复不长于您要替换的行,您还可以“修复”该行
If the other program can be changed to output the fileoffset instead of the line number, you can assign the offset to p directly and do without the for loop
如果其他程序可以改成输出fileoffset而不是行号,可以直接把offset赋值给p,不用for循环
import os
from mmap import mmap
phrase = 'the dog barked'
filename = r'C:\Path\text.txt'
def removeLine(filename, num):
f=os.open(filename, os.O_RDWR)
m=mmap(f,0)
p=0
for i in range(num-1):
p=m.find('\n',p)+1
q=m.find('\n',p)
m[p:q] = ' '*(q-p)
os.close(f)
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if phrase in line:
removeLine(filename, num)
print 'Removed at line:', num
回答by aar cee
Try
尝试
lines = myFile.readlines()
mylines = [x for x in lines if x.find(phrase) < 0]
回答by atomh33ls
Assuming num
is the line number to remove:
假设num
是要删除的行号:
import numpy as np
a=np.genfromtxt("yourfile.txt",dtype=None, delimiter="\n")
with open('yourfile.txt','w') as f:
for el in np.delete(a,(num-1),axis=0):
f.write(str(el)+'\n')
回答by Rob
I found another solution that works efficiently and gets by without doing all the icky and not so elegant counting of lines within the file object:
我找到了另一种有效工作的解决方案,无需对文件对象中的行进行所有令人讨厌且不那么优雅的计数:
del_line = 3 #line to be deleted: no. 3 (first line is no. 1)
with open("textfile.txt","r") as textobj:
list = list(textobj) #puts all lines in a list
del list[del_line - 1] #delete regarding element
#rewrite the textfile from list contents/elements:
with open("textfile.txt","w") as textobj:
for n in list:
textobj.write(n)
Detailed explanation for those who want it:
给想要的人详细解释:
(1) Create a variable containing an integer value of the line-number you want to have deleted. Let's say I want to delete line #3:
(1) 创建一个变量,其中包含要删除的行号的整数值。假设我想删除第 3 行:
del_line = 3
(2) Open the text file and put it into a file-object. Only reading-mode is necessary for now. Then, put its contents into a list:
(2) 打开文本文件并将其放入文件对象中。目前只需要阅读模式。然后,将其内容放入一个列表中:
with open("textfile.txt","r") as textobj:
list = list(textobj)
(3) Now every line should be an indexed element in "list". You can proceed by deleting the element representing the line you want to have deleted:
(3) 现在每一行都应该是“list”中的一个索引元素。您可以通过删除代表要删除的行的元素来继续:
del list[del_line - 1]
At this point, if you got the line no. that is supposed to be deleted from user-input, make sure to convert it to integer first since it will be in string format most likely(if you used "input()").
在这一点上,如果你得到了行号。应该从用户输入中删除,请确保首先将其转换为整数,因为它很可能是字符串格式(如果您使用了“input()”)。
It's del_line - 1 because the list's element-index starts at 0. However, I assume you (or the user) start counting at "1" for line no. 1, in which case you need to deduct 1 to catch the correct element in the list.
它是 del_line - 1 因为列表的元素索引从 0 开始。但是,我假设您(或用户)从“1”开始计数行号。1,在这种情况下,您需要减去 1 才能捕获列表中的正确元素。
(4) Open the list file again, this time in "write-mode", rewriting the complete file. After that, iterate over the updated list, rewriting every element of "list" into the file. You don't need to worry about new lines because at the moment you put the contents of the original file into a list (step 2), the \n escapes will also be copied into the list elements:
(4) 再次打开列表文件,这次是“写模式”,重写完整文件。之后,迭代更新的列表,将“列表”的每个元素重写到文件中。您无需担心换行,因为在将原始文件的内容放入列表(第 2 步)的那一刻,\n 转义符也将复制到列表元素中:
with open("textfile.txt","w") as textobj:
for n in list:
textobj.write(n)
This has done the job for me when I wanted the user to decide which line to delete in a certain text file. I think Martijn Pieters's answer does sth. similar, however his explanation is to little for me to be able to tell.
当我希望用户决定在某个文本文件中删除哪一行时,这对我来说已经完成了工作。我认为 Martijn Pieters 的回答确实如此。类似,但是他的解释对我来说几乎无法分辨。