【问题标题】:Write a program that asks the user for a file containing a program and a name for an output file.编写一个程序,要求用户提供一个包含程序和输出文件名称的文件。
【发布时间】:2015-03-25 21:34:24
【问题描述】:

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

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】:

    您可能希望使用enumerate 来遍历文件中的每一行:

    for line_number, line in enumerate(readfile):
        new_line = ???        # make the new line by adding a line number
        readfile[line_number] = new_line
    

    【讨论】:

      【解决方案2】:

      通过enumerate迭代输入文件的每一行,并通过字符串格式将内容写入新文件。

      输入文件

      input2.txt

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

      代码:

      filename = raw_input("Please enter a file name: ")
      filename2 = raw_input("Please enter a file name to save the output: ")
      
      openfile = open(filename, "r")
      readfile = openfile.readlines()
      
      
      out_file = open(filename2, "w")
      for i , line in enumerate(readfile):
          out_file.write("%d %s" %(i+1, line))
      
      out_file.close()
      

      输出:

      vivek@vivek:~/Desktop/stackoverflow/anna$ python 7.py 
      Please enter a file name: input2.txt
      Please enter a file name to save the output: output2.txt
      

      输出文件

      output2.txt

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

      with 声明。

      filename = raw_input("Please enter a file name: ")
      filename2 = raw_input("Please enter a file name to save the output: ")
      
      with open(filename, "r") as fp:
          with open(filename2, "w") as fp2:
              for i , line in enumerate(fp.readlines()):
                  fp2.write("%d %s" %(i+1, line))
      

      注意:

      在 Python 2.x 中使用 raw_input()

      在 Python 3.x 中使用 input()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        相关资源
        最近更新 更多