Skip to content Skip to sidebar Skip to footer

Setting Multiple Variables From Opened File - Python

I open a file using a python programme. file = open('test.txt', 'r') Then I set a variable: data = file.read() And another one: data2 = file.readlines() The data variable should

Solution 1:

When you open a file it returns a file pointer. This means that you can only read each line once. After you use read(), it reads the entire file, moving the file pointer to the end. Then when you use readlines() it returns an empty list because there are no lines past the end of the file.

Solution 2:

You have consumed the iterator with file.read() so there is nothing left to consume when you call readlines, you would need to file.seek(0) before the call to readlines to reset the pointer to the start of the file.

withopen('test.txt') as f: # with closes your files automatically
    data = f.read() 
    f.seek(0) # reset file pointer
    data2 = f.readlines() 

Solution 3:

It's not so much that setting data interferes with data2. Rather, it is calling file.read() interfering with file.readlines().

When you opened the file with file = open('test.txt', 'r'), the variable file is now a pointer to the file.

Thus, when you call file.read() or file.readlines(), it moves the pointer file.

file.read() moves the pointer to the end of the file, so there is no more like to read for file.readlines().

Even though you are assigning them to different variable, they ultimately depend on file. So by setting data, you modify file which interferes with your attempt to set data2.

Solution 4:

Why don't you split the string instead of reading the file again.

file = open('test.txt', 'r')
data = file.read()
data2 = data.split('\n')

Post a Comment for "Setting Multiple Variables From Opened File - Python"