如何将行号添加到输出文件? [英] How to add line numbers to an output file?

查看:170
本文介绍了如何将行号添加到输出文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写一个程序,要求用户输入一个包含程序和输出文件名称的文件。然后你的程序应该写入程序,用行号输出文件。例如,如果输入文件是:

  def main():
(i)在范围内(10):
print(我爱蟒蛇)
print(Good bye!)



然后输出文件是:

  1 def main():
2 for i in range 10):
3 print(我爱蟒蛇)
4 print(Good bye!)

我知道如何创建一个新的输出文件,但我很难在每行添加行号。请帮忙!我的程序是:

$ $ $ code $ filename $ input $($)请输入文件名以保存输出:)

openfile = open(filename,r)
readfile = openfile.readlines()


out_file = open(filename2,w)
save = out_file.write(FileWithLines)


和... 语法( https://docs.python.org/2/tutorial/inputoutput.html )。然后,你只需使用枚举 https://docs.python.org/2/library/functions.html#enumerate )。 enumerate 是一个内置函数,它将一个序列(string,list,dict,set,...)作为输入,并生成带有计数器的元组,并生成相应的值(开头文件名r)作为开放文件:
开放(文件名2,w)。

  )as out_file:
for j,enumerate(openfile)中的行:
out_file.write('{0:< 5} {1}'.format(j + 1,line))


Write a program that asks the user for a file containing a program and a name for an output file. Your program should then write the program, with line numbers to the output file. For example, if the input file is:

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

Then the output file would be:

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

I know how to create a new output file but I have difficulty in adding line numbers to each line. please help! My program is:

filename = input("Please enter a file name: ")
filename2 = input("Please enter a file name to save the output: ")

openfile = open(filename, "r")
readfile = openfile.readlines()


out_file = open(filename2, "w")
save = out_file.write(FileWithLines)

解决方案

First, it is best to use the with ... syntax when using files (https://docs.python.org/2/tutorial/inputoutput.html).

Then, all you have to do is use enumerate (https://docs.python.org/2/library/functions.html#enumerate). enumerate is a built-in function that takes a sequence (string, list, dict, set, ...) as input and generates tuples with a counter and the corresponding value of the sequence.

with open(filename, "r") as openfile:
    with open(filename2, "w") as out_file:
        for j, line in enumerate(openfile):
            out_file.write('{0:<5}{1}'.format(j+1, line))

这篇关于如何将行号添加到输出文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆