在Python中向输出中添加行号



例如,如果输入文件是:

def main():
    for i in range(10):
        print("I love Python")
    print("Good bye!")

那么输出将是:

1   def main():
2       for i in range(10):
3           print("I love Python")
4       print("Good bye!")

我很难把每一行都加起来。我的程序是:

filename = input("Please enter a file name: ")
count = 0
openfile = open(filename, "r")
for lines in openfile:
    linenumbers = openfile.write(str(count)+'t'+lines)
    count += 1
print(count)

使用with语句关闭文件缓冲区并连接字符串:

with open('file.txt', 'r') as program:
    data = program.readlines()
with open('file.txt', 'w') as program:
    for (number, line) in enumerate(data):
        program.write('%d  %s' % (number + 1, line))

您应该添加:

newFile = open(yourfile, 'w')
count = 1
for line in readfile:
    newFile.write (str(count) + 't' + line)
    count += 1
newFile.close()

如果你只想打印到控制台写入(这是根据你在第二次编辑中使用的变量名):

for lines in openfile:
    print str(count) + 't' + lines
    count += 1

不过你应该自己做作业!

我会这样写:

with open(path) as src:
    for index, line in enumerate(src.readlines(), start=1):
        print '{:4d}: {}'.format(index, line.rstrip())

with open(path) as src:
    print 'n'.join(['{:4d}: {}'.format(i, x.rstrip()) for i, x in enumerate(src.readlines(), start=1)])

最新更新