>>> girl
<_io.TextIOWrapper name='D:\\python\\works\\girl_3.txt' mode='w' encoding='cp936'>
>>> fgirl3
<_io.TextIOWrapper name='D:\\python\\works\\girl_3.txt' mode='w' encoding='cp936'>
>>> girl==fgirl3
False
The process of how the variables were given the values:
f=open(r'D:\python\works\record.txt')
fboy1=open(r'D:\python\works\boy_1.txt','w')
fboy2=open(r'D:\python\works\boy_2.txt','w')
fboy3=open(r'D:\python\works\boy_3.txt','w')
fgirl3=open(r'D:\python\works\girl_3.txt','w')
fgirl2=open(r'D:\python\works\girl_2.txt','w')
fgirl1=open(r'D:\python\works\girl_1.txt','w')
for num in range(3):
boy=[fboy1,fboy2,fboy3][num]
girl=[fgirl1,fgirl2,fgirl3][num]
(I tried to insert the codes as code, but it's a failure when I clicked the referred button.)
Each call to open() creates a new instance of _io.TextIOWrapper
. By default, Python objects compare equal if they are the same instance. The equality between open files objects has not been defined as the equality of the files' contents.
You are comparing file-object and not the actual value.
file-object create new instance and will be
False
as it's stored in different memory addresses.
Example.
boy = 'Kent'
fboy1 = open(r'boy_1.txt', 'w')
fboy1.write(boy)
fboy2 = open(r'boy_2.txt', 'w')
fboy2.write(boy)
fboy1.close()
fboy2.close()
boy_1 = open('boy_1.txt')
boy_2 = open('boy_1.txt')
Test
>>> boy_1
<_io.TextIOWrapper name='boy_1.txt' mode='r' encoding='UTF-8'>
>>> boy_1 == boy_2
False
>>> # Now read file-object and compare actual value
>>> boy_1.read()
'Kent'
>>> boy_1.read() == boy_2.read()
True
Advisable is when read/write is to use
with open()
(no need to close file-object),
and your encoding is strange(
cp936
) as OS guess wrong(
always utf-8
) or Unicode can be wrong.
Here a example of this.
boy = 'Tom'
test_uni = '教えてもらった'
with open('b1.txt', 'w', encoding='utf-8') as f_out:
f_out.write(f'{boy}\n')
f_out.write(test_uni)
with open('b1.txt', encoding='utf-8') as f:
print(f.read())
Output:
Tom
教えてもらっ