无法确定如何将行号添加到文本fi

2024-10-01 22:39:44 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想出了如何将原始文本写入一个新文件,但我仍然无法确定从何处开始在每行添加行号

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

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

Tags: 文件text文本txtnewclosereadmake
3条回答

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

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))

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

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

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

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)

相关问题 更多 >

    热门问题