3

In order to extract some values from this file :

enter image description here

I need to read it line by line. I tried to read line by line first but i don't know why it doesn't work.

I tried this :

#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file.readline():
    print line

EDIT:

Problem: working but not showing this lines (this is the file) enter image description here

Just the last line of them which is: (this is what is generated) enter image description here

c.ceti
  • 183
  • 2
  • 5
  • 12

4 Answers4

2

You might want to use a context manager with that to automatically close your opened file after the lines have been read, that is to ensure nothing unexpected happens to your file while python is processing it.

with open('/home/results/err.txt', 'r') as file:
for line in file:
    print line

readline() would read your file line-by-line but iterating over that would print the letters individually.

spencer
  • 179
  • 10
1

You need to iterate through the file rather than the line:

#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file:
    print line

file.readline() only reads the first line. When you iterate over it, you are iterating over the characters in the line.

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
1

file.readline() already reads one line. Iterating over that line gives you the individual characters.

Instead, use:

for line in file:
    …
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
1

Try this :

#! /usr/bin/python
file = open('/home/results/err.txt')
for line in file.readlines():
    print line
OzOm18
  • 2,191
  • 1
  • 8
  • 9