I have two files:
test1.txt's content:
test_outside_1
test_outside_2
test_outside_3
test2.txt's content:
test_inside_1
test_inside_2
test_inside_3
Here is my Python code:
fobj1 = open('test1.txt', 'r')
fobj2 = open('test2.txt', 'r')
for aline in fobj1.readlines():
print aline
for bline in fobj2.readlines():
print bline
the output I expected is:
test_outside_1
test_inside_1
test_inside_2
test_inside_3
test_outside_2
test_inside_1
test_inside_2
test_inside_3
test_outside_3
test_inside_1
test_inside_2
test_inside_3
But when I run my Python code the output is:
test_outside_1
test_inside_1
test_inside_2
test_inside_3
test_outside_2
test_outside_3
Could somebody tell me how to fix it?
When you do file.readlines()
, you read the complete file and the cursor is at the end of the file, trying to call file.readlines()
again on it would return an empty list, since there are no more lines to be read from the file.
One thing you can do is to store each in a list and iterate over the list. Example -
with open('test1.txt', 'r') as fobj1 , open('test2.txt', 'r') as fobj2:
alist = fobj1.readlines()
blist = fobj1.readlines()
for aline in alist:
print aline
for bline in blist:
print bline
Though please note reading complete files into memory may not be a good idea if the files are large. And there may be better ways depending on what your end goal is.
It's Occur because of in first iteration for test1.txt, test2.txt are read all then no other are exist for read test2.txt
You can also do it:
fobj1 = list(open('test1.txt', 'r'))
fobj2 = list(open('test2.txt', 'r'))
for aline in fobj1:
print aline
for bline in fobj2:
print bline
As answer @Anand S Kumar in the first loop you read the completes files in one loop, the it return and empty list.
If you don't want to store all file (as said could be a bad idea) you will have to open again your file.
with open('test1.txt', 'r') as fobj1:
for aline in fobj1.readlines():
print aline
with open('test2.txt', 'r') as fobj2:
for bline in fobj2.readlines():
print bline
but you will call a lot of time open.
EDIT: After commentary of #Anand is right.
If you want to keep memory low you should do something like
aline="."
with open('test1.txt', 'r') as fobj1:
while aline != "":
aline = fobj1.readline()
print aline
bline="."
with open('test2.txt', 'r') as fobj2:
while bline != "":
bline = fobj2.readline()
print bline
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.