1

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 be a string and data2 a list. Printing data works fine, but when I try to print data2, I get an empty list. Why does it work like that? Why does setting data iterfere with data2?

1
  • What's in the file and how do you want it to be stored in your program? Commented Aug 11, 2015 at 20:30

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

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

2 Comments

Is there any way I can do that, or do I have to close the file and re-open it?
@ZeroFunter, no worries, I presume this is just some experimentation?
1

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.

Comments

1

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')

1 Comment

Not the answer I was searching for, as I wanted to know why it worked like that, but that would definitelly work as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.