0

MyData.txt is a tab delimited file. It has 3 lines that look like this.

Adam 124 145

Beth 121 206

Andy 049 294

In the code below, I understand why the second for loop works (where i'm looping through "data"). I'm trying to understand why the first for loop part doesn't work. What does it mean to loop though "myfile" and why won't it print any values.

myfile = open("MyData.txt", "r")
data = myfile.readlines()

# This part doesn't work
for line in myfile:
    print(line)

# This part does!
for line in data:
    print(line)

myfile.close()
  • 3
    Try to remove the `data = ..` line and see what happens. – Anton vBR Dec 25 '17 at 21:08
  • 2
    `readlines` consumes the buffer. `data` is a `list` so it's a copy of the contents. voilà – Jean-François Fabre Dec 25 '17 at 21:09
  • @AntonvBR omg, that actually works! So what's the difference between using readlines() and just using looping through "myfile" here! – NumberCruncher Dec 25 '17 at 21:12
  • 1
    @NumberCruncher Well what you have is an iterable. You can read it (scan through start to end) to memory with the readlines() function or just loop over it. Depends what you want to do. One more thing: In Python you can use the `with open(....)` statement to open files which will make sure they are closed. Look it up! – Anton vBR Dec 25 '17 at 21:13
  • 1
    use `file.tell()` where in the file you are. using `readlines()` will place you at the end so there is no more data to read.use `myfile.seek(0)` to position yourself at the start of the file again. its simple stream stuff. see [methods-of-file-objects](https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects) – Patrick Artner Dec 25 '17 at 21:15
  • @NumberCruncher It is all described in the official documentation. Look here: https://docs.python.org/3.6/tutorial/inputoutput.html – Anton vBR Dec 25 '17 at 21:17
  • good stuff. @AntonvBR please answer – yeg Dec 25 '17 at 21:19
  • @AntonvBR That makes sense. Thanks very much for the links – NumberCruncher Dec 25 '17 at 21:31

3 Answers3

1

With

myfile = open("MyData.txt", "r")

you open a file handle, and

data = myfile.readlines()

reads all of the files content, meaning until the end of the file is reached.

Since after this, you reached the end of the file, there is nothing left to read from myfile in your first for loop, while you can iterate through the already read data as often as you like.

Elmar Peise
  • 14,014
  • 3
  • 21
  • 40
1

There are numerous ways to read the content of a file and this answer could be infinite. The file objects have built in methods you can use. See this for instance: https://docs.python.org/3.6/tutorial/inputoutput.html#methods-of-file-objects

read()

method that reads all the content to one string


readlines()

method that reads all lines to a list (you are now at the end of the file)


readline()

method that reads one line (you are now on next row)


for row in file: ...

For loop (iterator) over the file. This will read it line by line See: How to read large file, line by line in python for instance.


So why not one way? Simply because there are tons of ways to read and write the data. Depending on the situation you will most likely want to use a different approach.

My personal favourite for smaller files is using .read() like this:

data = '''\
Adam 124 145
Beth 121 206
Andy 049 294'''

# Let's recreate the file
with open('MyData.txt','w') as f:
    f.write(data)

# Open file with 'with' to ensure it is closed
# Read the whole content and split it with '\n' linbreak
# Use a list comprehension

with open('MyData.txt','r') as f:
    data = [i.split(' ') for i in f.read().split('\n')] # Change ' ' to '\t' for tab

data variable is now:

[['Adam', '124', '145'], ['Beth', '121', '206'], ['Andy', '049', '294']]
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
0

Whenever you use readlines or iterate over a file pointer , the position will be changed!

When you call myfile.readlines() , the position is changed to the end and thus when you iterate , there is no output , use myfile.tell() to find the position of your file pointer!

fp = open("Data.txt" , "r")
data = fp.readlines()
pos = fp.tell()

print("Position of File Pointer:: {}".format(pos))

Solution

You need to open the file twice. you can also use with

antonyjr
  • 61
  • 1
  • 5