我有一个文本文件,可以在Python中打开。
with open("database.txt", mode = "r") as text_file:
print ("\tDatabase: ")
for line in text_file:
print ("\t\t"+line[22:])
现在输出如下:
Database:
[Sandy] [20]
[Patrick] [5]
[Spongebob] [125]
[Squid] [1200]
[Garry] [1]
我的问题是我需要向从1到列表长度的每一行添加索引。
Database:
1. [Sandy] [20]
2. [Patrick] [5]
n. [MrKrabs] [42]
之后,我必须能够更改与索引对应的行。
Choose index you want to change: 1
Write down the name and the number: [MrsPuff] [300]
现在数据库变成
Database:
[MrsPuff] [300]
[Patrick] [5]
[Spongebob] [125]
[Squid] [1200]
[Garry] [1]
并且要求索引仅在Python中显示。实际的txt文件数据库没有它们。
我希望我能找到帮助,因为我已经尝试了几个小时,但仍然无法解决。
使用枚举功能,打印部分相对容易:
with open("database.txt", mode = "r") as text_file:
for iline, line in enumerate(text_file, 1):
print iline, line
请注意,使用第二个参数从1开始编号,因为在Python中索引通常基于0。您需要再次从用户输入中减去1,以稍后修改正确的行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句