python删掉txt第一列,使用Python从文本文件中删除一行

I have a file where each line starts with a number. The user can delete a row by typing in the number of the row the user would like to delete.

The issue I'm having is setting the mode for opening it. When I use a+, the original content is still there. However, tacked onto the end of the file are the lines that I want to keep. On the other hand, when I use w+, the entire file is deleted. I'm sure there is a better way than opening it with w+ mode, deleting everything, and then re-opening it and appending the lines.

def DeleteToDo(self):

print "Which Item Do You Want To Delete?"

DeleteItem = raw_input(">") #select a line number to delete

print "Are You Sure You Want To Delete Number" + DeleteItem + "(y/n)"

VerifyDelete = str.lower(raw_input(">"))

if VerifyDelete == "y":

FILE = open(ToDo.filename,"a+") #open the file (tried w+ as well, entire file is deleted)

FileLines = FILE.readlines() #read and display the lines

for line in FileLines:

FILE.truncate()

if line[0:1] != DeleteItem: #if the number (first character) of the current line doesn't equal the number to be deleted, re-write that line

FILE.write(line)

else:

print "Nothing Deleted"

This is what a typical file may look like

1. info here

2. more stuff here

3. even more stuff here

解决方案def DeleteToDo():

print ("Which Item Do You Want To Delete?")

DeleteItem = raw_input(">") #select a line number to delete

print ("Are You Sure You Want To Delete Number" + DeleteItem + "(y/n)")

DeleteItem=int(DeleteItem)

VerifyDelete = str.lower(raw_input(">"))

if VerifyDelete == "y":

FILE = open('data.txt',"r") #open the file (tried w+ as well, entire file is deleted)

lines=[x.strip() for x in FILE if int(x[:x.index('.')])!=DeleteItem] #read all the lines first except the line which matches the line number to be deleted

FILE.close()

FILE = open('data.txt',"w")#open the file again

for x in lines:FILE.write(x+'\n') #write the data to the file

else:

print ("Nothing Deleted")

DeleteToDo()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值