+ 2

[Solved] Questions about readlines():

A) Given 1) file.readlines() and file.readlines(0) return all the lines and 2) file.readlines(x), x: x != 0 return the first line of file = open('notes.txt', 'r'), Is it the case that what amounts to "0" and "anything but zero" respectively in the readlines argument are in fact the logic cases True and False, and True in this case is default "all the list items" and false by default is not "not all the list items" but "the first list item"? I kept trying stuff on my app and I can't make any other sense of this. Can you confirm or deny and explain? B) If you have 2 lines in notes.txt, print(file.readlines(500)) print(file.readlines()[1]) file.close() are run at once, it throws an "index is out of range" exception for the 2nd one. When you run each separately by hashing out the other, you get ["Line 1\n"] and ['Line 2\n'] respectively. So why the error when they are run together? Does that mean the first one does not just pick the 1st line but also truncates the list of lines to itself? Mutability?

1st Apr 2022, 7:23 PM
Korkunç el Gato
Korkunç el Gato - avatar
7 Answers
+ 4
readlines Description Returns a list containing lines from the file. Syntax file. readlines([sizehint]) sizehintOptional. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Remarks Reads lines until EOF using readline() and return a list containing the lines thus read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently. Return Value list Source: https://python-reference.readthedocs.io/en/latest/docs/file/readlines.html
1st Apr 2022, 8:16 PM
Paul K Sadler
Paul K Sadler - avatar
+ 5
Korkunç TheTerrible , ok - i understand. but you can tell us why you are using the argument with readlins(). what do you want to achieve with this?
1st Apr 2022, 8:31 PM
Lothar
Lothar - avatar
+ 4
Paul K Sadler Thanks for the link. It's kind of advanced for me, but I now know what words to look up, I think.
1st Apr 2022, 8:22 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 3
Korkunç TheTerrible , please link thex code you used here. thanks!
1st Apr 2022, 8:12 PM
Lothar
Lothar - avatar
+ 3
Lothar I was just trying to see what would happen if I did that. I was expecting an error but I got an output instead which then intrigued me. This is part of a. py file that I prepared to remind me what's what in case I forgot, because I do forget. In short I was trying to understand how it works, and also retain that information.
1st Apr 2022, 8:52 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 2
Lothar I used it on my app, not here. I did copy it in here but because it opens a file on my device, it cannot be run. If you still want to see it, I can link it though.
1st Apr 2022, 8:15 PM
Korkunç el Gato
Korkunç el Gato - avatar