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()"
8 Answers
+ 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.
+ 4
The file object is iterable, not the file. The file object is returned by the open() function.
+ 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.
+ 3
Right, they are not "indexable", but we could reset the cursor.
https://stackoverflow.com/a/16994568
+ 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.
+ 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")
+ 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.
+ 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.