Python 从文本文档中删除行
我目前正在为学校作业制作一个脚本,它有很多功能,但我一直坚持的是删除功能。 基本上,它需要做的是从现有的10行中删除用户想要的一行(我们只能允许写入10行)。 例如,如果文档具有:Python 从文本文档中删除行,python,python-3.x,Python,Python 3.x,我目前正在为学校作业制作一个脚本,它有很多功能,但我一直坚持的是删除功能。 基本上,它需要做的是从现有的10行中删除用户想要的一行(我们只能允许写入10行)。 例如,如果文档具有: 1 2 3 4 5 6 7 8 9 10 我试着删除8,它会这样重写: 1 2 3 4 5 6 7 9 10 我现在的代码在这里 elif action1 == '2': linetoremove = input('What line would you like to remove? (1 up
1
2
3
4
5
6
7
8
9
10
我试着删除8,它会这样重写:
1
2
3
4
5
6
7
9
10
我现在的代码在这里
elif action1 == '2':
linetoremove = input('What line would you like to remove? (1 up to 10)')
with open('highscore.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('highscore.txt', 'w') as fout:
fout.writelines(data[int(linetoremove)]:)
删除第1行很好,但上面的任何数字都将删除下面的所有数字。
我知道这样的删除应该发生,但我找不到这样做的方法只有1行被删除
谢谢
Conn使用
枚举
迭代每行文本,并获取其在文件中的位置:
with open('highscore.txt', 'w') as fout:
for line_number, line in enumerate(data):
if line_number != int(linetoremove):
fout.write(line)
python中的数组(列表和元组)以索引0开始,而不是1。这就是为什么当用户输入“1”时,您的代码似乎成功地删除了第一行。编写时,您的代码只打印由linetoremove索引的行
linetoremove = input('What line would you like to remove? (1 up to 10)')
with open('highscore.txt', 'r') as fin:
data = fin.read().splitlines(True)
del data[int(linetoremove)-1]
with open('highscore.txt', 'w') as fout:
fout.writelines(data)
您还可以验证输入的值。不应该在这里询问家庭作业的答案,但我感觉很好!不是最有效或最快的,但我认为它会向您展示最好的步骤
def removeLine(line, file):
f1 = open(file, 'rb').readlines() #Creates a list of the lines in the file, automatically closes file
try:
del f1[line-1] #Attempt to delete the line at index
except:
print 'Line %s does not exist in %s'%(line, file) #Print and return if it cannot
return
f2 = open(file, 'wb') #open new instance of the file in write mode
for i in f1:
f2.write(i) #write to the file
f2.close() #Close file
removeLine(5, 'data')
要理解代码不起作用的原因,您可能需要仔细阅读
假设用户输入“4”作为要删除的行号,这将导致将以下片段发送到您的writelines
data[4:]
我们可以通过下面的例子来了解这一点
data = [0, 1, 2, 3, 4, 5, 6, 7, 8]
data[4:] # [4, 5, 6, 7, 8]
简而言之,它返回索引大于或等于4的数据中所有值的列表。(注意,第一个元素的索引为0。)
这可以与互补片组合以执行类似移除的操作
data = [0, 1, 2, 3, 4, 5, 6, 7, 8]
data[:3] + data[4:] # [0, 1, 2, 4, 5, 6, 7, 8]
请注意,我将此操作称为类似删除的操作,因为它是创建新列表,而不是编辑现有列表。要修复代码,可以执行以下操作:
index = int(linetoremove) - 1
fout.writelines(data[:index] + data[index+1:])
@ConnB-M您在问题中定义了data
。data=fin.read()
注意data[int(linetoremove)]:
应该是data[int(linetoremove):]
,否则您的代码会引发一个SyntaxError
。
index = int(linetoremove) - 1
fout.writelines(data[:index] + data[index+1:])