如何将索引添加到txt文件输出,然后使用索引Python修改行

时间:2015-11-29 09:21:53

标签: python file text

我有一个文本文件,我可以用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文件数据库没有它们。

我希望我能找到帮助,因为我已经尝试了几个小时但仍然无法管理它。

2 个答案:

答案 0 :(得分:0)

使用enumerate功能打印部件相对容易:

with open("database.txt", mode = "r") as text_file:
    for iline, line in enumerate(text_file, 1):
        print iline, line

注意使用第二个参数来开始编号为1,因为索引在Python中通常是基于0的。您需要再次从用户输入中减去1,以便稍后修改正确的行...

答案 1 :(得分:-1)

h = file('db.txt', 'r')
lines = h.read().split('\n')
h.close()
for index, line in enumerate(lines):
    print index, line
相关问题