非常自我解释。这是我的文本文件:
C:\Windows\Users\Public\Documents\
C:\Program Files\Text Editor\
所以,我有代码提示用户输入他想要删除的行号。但是如何删除与数字对应的行?
编辑:
询问代码的人:
# Viewing presets
if pathInput.lower() == 'view':
# Prints the lines in a numbered, vertical list.
numLines = 1
numbered = ''
for i in lines:
i = str(numLines) + '. ' + i
numbered += i
print (i)
numLines += 1
viewSelection = input('\n^ Avaiable Paths ^\nInput the preset\'s number you want to perform an action on.\n')
for i in numbered:
if viewSelection in i:
viewAction = input('\nInput action for this preset.\nOptions: "Delete"')
if viewAction.lower() == 'delete':
我只想要一种方法来删除文件中的行号。
答案 0 :(得分:0)
一种简单的方法是将行读入列表,更新列表,然后将其写回同一文件。像这样:
with open("file.txt", "r+") as f:
lines = f.readlines()
del lines[linenum] # use linenum - 1 if linenum starts from 1
f.seek(0)
f.truncate()
f.writelines(lines)