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
JavaScript
x
10
10
1
a=open("file1.txt")
2
NumberofLines = 2
3
with open("file2.txt","w") as b:
4
for i in range (NumberofLines):
5
line = a.readline()
6
b.write(line + "/n")
7
print(b)
8
a.close()
9
b.close()
10
But this is not working and I can’t find the error. please help
Advertisement
Answer
JavaScript
1
14
14
1
NumberofLines = 2
2
3
# open the 2 files in the same time
4
# NOTE: when we use with there is no need for file.close()
5
with open('file1.txt', 'r') as f1, open('file2.txt','w') as f2:
6
for _ in range(NumberofLines):
7
# read the line from f1 and write it into f2
8
# NOTE: no need for 'n' because the line we read will have it
9
f2.write(f1.readline())
10
11
# open file2 and read its content
12
with open('file2.txt','r') as f3:
13
print(f3.read())
14