简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM