[英]How to delete a line from a text file using the line number in python
这是一个示例文本文件
the bird flew
the dog barked
the cat meowed
这是我的代码,用于查找我要删除的短语的行号
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
我可以添加什么才能删除我尝试过的行号(num)
lines = myFile.readlines()
del line[num]
但这不起作用我应该如何解决这个问题?
您可以使用fileinput
模块来更新文件 - 请注意,这将删除包含该短语的所有行:
import fileinput
for line in fileinput.input(filename, inplace=True):
if phrase in line:
continue
print(line, end='')
一位名叫 gnibbler 的用户在另一个线程上发布了类似的内容。
就地修改文件,有问题的行被替换为空格,因此文件的其余部分不需要在磁盘上随意移动。 如果修复不长于您要替换的行,您还可以“修复”该行
如果其他程序可以改成输出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
我找到了另一种有效工作的解决方案,无需对文件对象中的行进行所有令人讨厌且不那么优雅的计数:
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)
给想要的人详细解释:
(1) 创建一个变量,其中包含要删除的行号的整数值。 假设我想删除第 3 行:
del_line = 3
(2) 打开文本文件并将其放入文件对象中。 目前只需要阅读模式。 然后,将其内容放入一个列表中:
with open("textfile.txt","r") as textobj:
list = list(textobj)
(3) 现在每一行都应该是“list”中的一个索引元素。 您可以通过删除代表要删除的行的元素来继续:
del list[del_line - 1]
在这一点上,如果你得到了行号。 应该从用户输入中删除,请确保首先将其转换为整数,因为它很可能是字符串格式(如果您使用了“input()”)。
它是 del_line - 1 因为列表的元素索引从 0 开始。但是,我假设您(或用户)从“1”开始计数行号。 1,在这种情况下,您需要减去 1 才能捕获列表中的正确元素。
(4) 再次打开列表文件,这次是“写模式”,重写整个文件。 之后,迭代更新的列表,将“列表”的每个元素重写到文件中。 您无需担心换行,因为在将原始文件的内容放入列表(第 2 步)的那一刻,\\n 转义符也将复制到列表元素中:
with open("textfile.txt","w") as textobj:
for n in list:
textobj.write(n)
当我希望用户决定在某个文本文件中删除哪一行时,这对我来说已经完成了工作。 我认为 Martijn Pieters 的回答确实如此。 类似,但是他的解释对我来说几乎无法分辨。
假设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')
您从1开始计数,但 Python 索引始终从零开始。
从零开始您的行数:
for num, line in enumerate(myFile): # default is to start at 0
或者从num
减去一个,从lines
(不是line
)中删除:
del lines[num - 1]
请注意,为了让您的.readlines()
调用返回任何行,您需要先重新打开文件,或者寻找开头:
myFile.seek(0)
尝试
lines = myFile.readlines()
mylines = [x for x in lines if x.find(phrase) < 0]
实现@atomh33ls numpy 方法 所以你想删除文件中包含phrase
字符串的任何行,对吗? 而不是仅仅删除phrase
字符串
import numpy as np
phrase = 'the dog barked'
nums = []
with open("yourfile.txt") as myFile:
for num1, line in enumerate(myFile, 0):
# Changing from enumerate(myFile, 1) to enumerate(myFile, 0)
if phrase in line:
nums.append(num1)
a=np.genfromtxt("yourfile.txt",dtype=None, delimiter="\n", encoding=None )
with open('yourfile.txt','w') as f:
for el in np.delete(a,nums,axis=0):
f.write(str(el)+'\n')
文本文件在哪里,
the bird flew
the dog barked
the cat meowed
产生
the bird flew
the cat meowed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.