[英]How do I delete a certain line (given a line #) in a file through python?
I want to delete a line of text from a .txt file given an integer corresponding to the txt file's line number.我想从 .txt 文件中删除一行文本,给定一个与 txt 文件的行号相对应的整数。 For example, given the integer 2, delete line 2 of the text file.
例如,给定整数 2,删除文本文件的第 2 行。 I'm sort of lost on what to put into my program.
我有点迷失在我的程序中加入什么。
f = open('text1.txt','r+')
g = open('text2.txt',"w")
line_num = 0
search_phrase = "Test"
for line in f.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
print("text found a line" , line_num)
decision = input("enter letter corresponding to a decision: (d = delete lines, s = save to new txt) \n")
if decision == 'd':
//delete the current line
if decision == 's':
//save the current line to a new file
Any help is appreciated!任何帮助表示赞赏! Thanks :)
谢谢 :)
This way:这边走:
with open('text1.txt','r') as f, open('text2.txt',"w") as g:
to_delete=[2,4]
for line_number, line in enumerate(f.readlines(), 1):
if line_number not in to_delete:
g.write(line)
else:
print(f'line {line_number}, "{line.rstrip()}" deleted')
Here it goes.就这样吧。
f = open('data/test.txt','rb')
text = f.readlines() # all lines are read into a list and you can acess it as a list
deleted_line = text.pop(1) #line is deleted and stored into the variable
print(text)
print(deleted_line)
f.write(text) # here you save it with the new data, you can always delete the data in the file to replace by the new one
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.