Skip to content
Advertisement

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”

I need 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 called “file2.txt” Read “file2.txt” and Print the contents

a=open("file1.txt")
NumberofLines = 2
with open("file2.txt","w") as b:
    for i in range (NumberofLines):
        line = a.readline()
        b.write(line + "/n")
print(b)
a.close()
b.close()

But this is not working and I can’t find the error. please help

Advertisement

Answer

NumberofLines = 2

# open the 2 files in the same time
# NOTE: when we use with there is no need for file.close()
with open('file1.txt', 'r') as f1, open('file2.txt','w') as f2:
    for _ in range(NumberofLines):
        # read the line from f1 and write it into f2
        # NOTE: no need for 'n' because the line we read will have it
        f2.write(f1.readline())

# open file2 and read its content
with open('file2.txt','r') as f3:
    print(f3.read())
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement