Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can i read lines from file only one time?

Tags:

python

I have a file containing python's object as string, then i open it and doing things like i showing:

>>> file = open('gods.txt')
>>> file.readlines()
["{'brahman': 'impersonal', 'wishnu': 'personal, immortal', 'brahma': 'personal, mortal'}\n"]

But then i have problem because there is no longer any lines:

>>> f.readlines()
[]
>>> f.readline(0)
''

Why it is heppening and how can i stay with access to file's lines?

like image 983
krzyhub Avatar asked May 09 '12 19:05

krzyhub


People also ask

What is the method to read a single line at a time from the file?

The readline() method helps to read just one line at a time, and it returns the first line from the file given. We will make use of readline() to read all the lines from the file given. To read all the lines from a given file, you can make use of Python readlines() function.

How do I read 10 lines from a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.

How can you read an entire file and get each line?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

Does readline only read the first line?

readline() reads a single line -- the next line in the context of the iterator returned by open() .


2 Answers

Your position in the file has moved

f = open("/home/usr/stuff", "r")
f.tell()
# shows you're at the start of the file
l = f.readlines()
f.tell()
# now shows your file position is at the end of the file

readlines() gives you a list of contents of the file, and you can read that list over and over. It's good practice to close the file after reading it, and then use the contents you've got from the file. Don't keep trying to read the file contents over and over, you've already got it.

like image 22
Vernon Avatar answered Sep 30 '22 14:09

Vernon


There's only one line in that file, and you just read it. readlines returns a list of all the lines. If you want to re-read the file, you have to do file.seek(0)

like image 133
Stefano Borini Avatar answered Sep 30 '22 15:09

Stefano Borini