Home > Mobile >  How write python to Read the first two lines from a text file named "file1.txt" Write the
How write python to Read the first two lines from a text file named "file1.txt" Write the

Time:04-26

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"

CodePudding user response:

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

I'm sure there is a neater solution out there somewhere but this will work! Hope it helps you :)

CodePudding user response:

For 2 lines:

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

Each time r.readline() is called, it goes to the next line. So if you wanted to read n lines; use:

Note that .readline() r.readline() is only 2 seperate lines if there is a new line (\n) at the end of the first line

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())
  • Related