无法弄清楚如何在文本文件中添加行号

时间:2019-09-18 00:20:20

标签: python python-3.x

我需要获取一个文本文件并将其导入python,将该文件中的文本写入一个新文件,并在该文本文件的每一行中包含行号。

我想出了如何将原始文本写到新文件中,但是我在开始在每行上添加行号的问题上陷入了困境。

text = open('lab07_python.txt', 'r')
make = text.read()
text.close()

new = open('david.txt', 'w')
new.write(make)
new.close()

3 个答案:

答案 0 :(得分:1)

您需要遍历旧文件的各行,例如:

with open('lab07_python.txt', 'r') as old:
    lines = old.readlines()
    with open('david.txt', 'w') as new:
        for i, line in enumerate(lines):
            new.write("%d %s\n" % (i, line))

答案 1 :(得分:0)

通过添加一些字符串格式来解决:

total = 0
with open('lab07_python.txt', 'r') as orig:
    lines = orig.readlines()
    for line in lines:
        total = total +1
        new = '%d %s' % (total, line)
        david.write(new)

答案 2 :(得分:0)

这是完成这项任务的一种方法。

infile = open('infile.txt','r')
outfile = open('outfile.txt', 'w+')
line_number = 0
for line in infile.readlines():
  outfile.write(f'{line_number} {line}')
  line_number += 1

# infile text
# line 0
# line 1
# line 2
# line 3
# line 4
# line 5

# outfile text
# 0 line 0
# 1 line 1
# 2 line 2
# 3 line 3
# 4 line 4
# 5 line 5