【问题标题】:How to add line numbers to an output file?如何将行号添加到输出文件?
【发布时间】:2015-03-25 22:50:36
【问题描述】:

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

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

【问题讨论】:

标签: python text formatting


【解决方案1】:

首先,在使用文件时最好使用with ... 语法(https://docs.python.org/2/tutorial/inputoutput.html)。

然后,您所要做的就是使用enumerate (https://docs.python.org/2/library/functions.html#enumerate)。 enumerate 是一个内置函数,它以序列(字符串、列表、字典、集合...)作为输入,并生成带有计数器和序列对应值的元组。

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

【讨论】:

  • 在这里快速提及 enumerate 的返回值/类型将是一个很好的补充。那个和/或这个函数的文档页面会很棒! +1
  • 你能按我的方式做吗,好吗?我没有用语句学习
  • @malcolm with statements 将使您的生活更轻松,尤其是文件 I/O。这是了解with的绝佳时机!
  • @malcom,看看代码。就这么简单......之后无需关闭文件或做任何其他事情
  • 在文件 I/O 文档页面的底部附近,您会看到一个干净的 with 示例:docs.python.org/2/tutorial/inputoutput.html
【解决方案2】:

查看此question,它准确地描述了您正在寻找的内容。如果您需要更多详细信息,请告诉我。

【讨论】:

    猜你喜欢
    • 2018-06-08
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多