Why Can't I Call Read() Twice on an Open File

Why can't I call read() twice on an open file?

Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.

To answer your question directly, once a file has been read, with read() you can use seek(0) to return the read cursor to the start of the file (docs are here). If you know the file isn't going to be too large, you can also save the read() output to a variable, using it in your findall expressions.

Ps. Don't forget to close the file after you are done with it.

Read multiple times lines of the same file Python

Use file.seek() to jump to a specific position in a file. However, think about whether it is really necessary to go through the file again. Maybe there is a better option.

with open(name, 'r+') as file:
for line in file:
# Do Something with line
file.seek(0)
for line in file:
# Do Something with line, second time

Python Why use open(filename) twice in this code?

When you use the readlines function, it reads all the lines into memory and by the end of it the file pointer is at the very end of the file.

So if you try to readlines again after having used it already, since the file pointer is at the end it will read from the end to the end, hence the blank matrix.

They reopened the file so that the file pointer is back at the beginning. Another way of doing that is filevariable.seek(0) that will move the file pointer back to the start and you should be able to use readlines again.

One thing to note is that readlines reads the whole file into memory, if you have a massive file you should use a for loop and use readline to read one line at a time.

python's file.read() doesn't return the string inside the text file

The first call to read already consumes the whole string and throws it away, as it is only used in the if-statement. Only call file.read() once and save the string to a variable:

file = open("path to the file", "r")
s = file.read()
if s != "":
print("String is not empty, here's what it said: " + s)

Python: why does repeat of json.load cause error

try this:

JSON_DATA_UPDATE = json.loads(JSON_FILE_UPDATE)

once it is loaded, then the file converted to json. cannot convert json to json.

another way, this may work on string to json:

import ast

file = """{
"students": [
{
"name": "Millie Brown",
"active": False,
"rollno": 11
},
{
"name": "Sadie Sink",
"active": True,
"rollno": 10
}
]
}"""

print(type(file))
dict = ast.literal_eval(file)
print(type(dict))

dict['students'][0]['name'] would be "Millie Brown"
dict['students'][1]['active'] would be True


Related Topics



Leave a reply



Submit