Can't use the same read file as an argument twice in a row

Hi! So, when I was doing my Guided Project: Profitable App Profiles for the App Store and Google Play Markets, I just noticed that I can’t create two lists from the same read file, apparently. Notice that only the first one defined works properly.

When the variable “android” is first defined, “android_header” doesn’t work properly:

When the variable “android_header” is first defined, “android” doesn’t work properly:

I expected them to be the same thing. Does anyone know what’s going on?

Hi there,

That’s the expected behavior of using a file reader.

What’s happening is when you use reader(opened_android), you only get the csv_reader but not the data yet. The reader’s job is to read the data but it will not do so until something prompts it to start reading which in this case is list.

The reader works sequentially. Let’s say you have a file like so:

Start
App 1
App 2
App 3
End

When you call list(read_android), the reader will move and read each character until the end. When it’s at the end of the file, the reader will stop and stay there.

Start of reading:

(-> reader starts here)Start
App 1
App 2
App 3
End

End of reading:

Start
App 1
App 2
App 3
End(->reader is now here)

What happens if you call list(..) again? The reader will try to move, but since it’s already at the end it will return nothing.

If you want to set the reader back to the starting point, you’ll need to access the seek method of your opened file. For example, opened_android.seek(0).

opened_android = open('AppleStore.csv')
read_android = reader(opened_android)

android = list(read_android)
# rewind the reader to go back to start of file
opened_android.seek(0)
android_header = list(read_android)[0]

Another option is to just reuse your previous variable. For example:

android_header = list(read_android)
android = android_header

You can also read the following answers from people way smarter than me:

Feel free to correct me if I’m wrong, because I probably misread things somewhere.

2 Likes