PYTHON-在输出中添加行号

时间:2015-03-25 23:09:42

标签: python text format

例如,如果输入文件是:

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

我很难在每行添加行。请帮忙!我的节目是:

UPDATED***

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)

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

你应该添加:

newFile = open(yourfile, 'w')
count = 1

for line in readfile:
    newFile.write (str(count)+'\t'+line)
    count+=1
newFile.close()

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

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

你应该自己做你的作业!

答案 2 :(得分:0)

我会写的:

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