0

Are lines in a file indexed?

"You can also use a for loop to iterate through the lines in the file: file = open("filename.txt", "r") for line in file: print(line) file.close()"

31st Mar 2025, 8:43 AM
Igor Matić
Igor Matić - avatar
8 Antworten
+ 4
Igor Matić , no, lines in a file are not indexed. we can not access them randomly by using indexes. > each line in a file is stored as a string, including a newline character ``\n``. so we are able to read line by line. > python handles these *newline characters* as a line delimiter and separates the content accordingly.
31st Mar 2025, 9:07 AM
Lothar
Lothar - avatar
+ 4
The file object is iterable, not the file. The file object is returned by the open() function.
31st Mar 2025, 9:09 AM
Lisa
Lisa - avatar
+ 4
Igor Matić , to get (and may be process) a specific line of a text file, we can use a counter variable, a range or an enumerator. to get the 5th line from a file, iterate through the file until the counter reaches the target line.
31st Mar 2025, 10:56 AM
Lothar
Lothar - avatar
+ 3
Right, they are not "indexable", but we could reset the cursor. https://stackoverflow.com/a/16994568
31st Mar 2025, 10:24 AM
Lisa
Lisa - avatar
+ 3
Igor Matić if the file is reasonably small enough then you could read the entire file into a list by using file.readlines(). The list would let you access lines by index.
31st Mar 2025, 3:28 PM
Brian
Brian - avatar
+ 3
Igor Matić def get_line(filename, line_number): try: with open(filename, 'r') as file: lines = file.readlines() if 0 <= line_number < len(lines): return lines[line_number] else: return None #or raise an error, index out of range. except FileNotFoundError: return None #Or raise an error, file not found. #Example usage line = get_line("filename.txt", 2) #get the third line. if line: print(line) else: print("line not found")
1st Apr 2025, 8:50 PM
BroFar
BroFar - avatar
+ 2
Lothar thanks. I'm stuck on a practice task that asks me to print the specific line while never mentioning what exactly is used to refer to that specific line (user input), so i wanted to check if it's maybe index.
31st Mar 2025, 9:41 AM
Igor Matić
Igor Matić - avatar
+ 2
Lisa thank you, but i know that. The lesson i'm stuck on explains that, and explains how to open a certain number of bytes, but it doesn't tell how to distinguish lines from each other, and print a specific one. I thought that maybe indexes are used for that purpose.
31st Mar 2025, 9:49 AM
Igor Matić
Igor Matić - avatar