0

I suppose read() does read a file as a string, while readline() reads a file line by line. There's a size positional argument for the two method which default to -1 (read everything). Now my problem begins, isn't x.read() == x. readlines() since both defaults to -1 which reads everything?

Here's my code:

with open('some_file.png') as my_file:
    check = my_file.read()
     print(b'\x89PNG\r\n\x1a\n' in check) #all PNG files has the byte string. #This returned True
   check = my_file.readlines()
    print(b'\x89PNG\r\n\x1a\n' in check) #this one returned False 

I thought both should return True since I read everything without sizing. A good explanation would help. Thanks

faruk13
  • 1,276
  • 1
  • 16
  • 23

2 Answers2

3

read() returns a string with the contents of the file

readlines() returns a list of all the lines in the file

More:

hedy
  • 1,160
  • 5
  • 23
1

read() returns a string with a full content of the file. readlines() returns a list of the content of the file.

Let's take a look at an example:

test_list = ['abc', 'png start', 'temp']

test_str = ['abc png start temp']

And if you will test if png is in list you will get False, because it will try to find such element as a whole in elements of the list. If you will try to check if png start is in list you will get True. But for test_str in both cases you will get True.