【问题标题】:How write python to Read the first two lines from a text file named "file1.txt" Write the two lines read from "file1.txt" to a new file "file2.txt"如何编写python从名为“file1.txt”的文本文件中读取前两行将从“file1.txt”读取的两行写入新文件“file2.txt”
【发布时间】:2022-06-13 12:24:35
【问题描述】:

从名为“file1.txt”的文本文件中读取前两行,将从“file1.txt”中读取的两行写入新文件“file2.txt”

【问题讨论】:

    标签: python new-operator file-handling readlines console.writeline


    【解决方案1】:
    a_file = open("file1.txt", "r")
    number_of_lines = 2
    with open("file2.txt", "w") as new_file:
        for i in range(number_of_lines):
            line = a_file.readline()
            new_file.write(line)
    a_file.close()
    

    我确信某处有更简洁的解决方案,但这会奏效! 希望对你有帮助:)

    【讨论】:

      【解决方案2】:

      对于 2 行:

      with open("file1.txt", "r") as r:
          with open("file2.txt", "w") as w:
              w.write(r.readline() + r.readline())
      

      每次调用r.readline(),都会转到下一行。因此,如果您想阅读n 行;使用:

      请注意,如果第一行末尾有新行 (\n),.readline() + r.readline() 只有 2 个单独的行

      with open("file1.txt", "r") as r:
          with open("file2.txt", "w") as w:
              # Change 2 to number of lines to read
              for i in range(2):
                  w.write(r.readline())
      

      【讨论】:

        【解决方案3】:
        f1=open("file1.txt","r")
        f2=open("file2.txt","w")
        fcontent=f1.readline()
        f2.write(fcontent)
        fcontent=f1.readline()
        f2.write(fcontent)
        f1.close()
        f2.close()
        

        【讨论】:

          【解决方案4】:

          写一个Python程序来

          1. 从名为“file1.txt”的文本文件中读取前两行
          2. 将从“file1.txt”读取的两行写入一个名为 "file2.txt"
          3. 读取“file2.txt”并打印内容
          fhandle1 = open("file1.txt","r")
          fhandle2 = open("file2.txt","w")
          
          str = fhandle1.readline()
          fhandle2.write(str)
          str = fhandle1.readline()
          fhandle2.write(str)
          
          fhandle1.close()
          fhandle2.close()
          
          fhandle3 = open("file2.txt")
          print(fhandle3.read())
          fhandle3.close()
          

          【讨论】:

            【解决方案5】:

            #以阅读模式打开file1

            fhandle1 = open("file1.txt","r")
            

            #以写入模式打开file2

            fhandle2 = open("file2.txt","w")
            
            str = fhandle1.readline()
            fhandle2.write(str)
            str = fhandle1.readline()
            fhandle2.write(str)
            
            fhandle1.close()
            fhandle2.close()
            
            fhandle3 = open("file2.txt")
            print(fhandle3.read())
            fhandle3.close()
            

            【讨论】:

              猜你喜欢
              • 2017-10-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-02-20
              • 2021-07-15
              相关资源
              最近更新 更多