-2
infile = 'xyz.txt'

f = open(infile)
line = f.readline() # these lines are all read fine 
print("line=",line)
line = f.readline()
print("line=",line)
line = f.readline()
print("line=",line)
pause()
f.close()

with open(infile) as f: 
    line = f.readline() # this reads the first line but
    print("line=",line) # dies without a message on line 2
    pause()
sys.exit

def pause():
    c = input("\nEnter q to quit, anything else to continue\n") 
    if (c.lower()=='q'): sys.exit()
    return (c)

Adding arguments to open, like 'r', 'ignore', encoding, etc. make no difference.

It happens on other input files as well, so it's not input specific.

It dies even without the pause in the loop

After the first line, it prints the line and the pause message, and dies reading the second line.

Could this be a genuine compiler error?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
user1067305
  • 3,233
  • 7
  • 24
  • 29
  • 2
    There is no loop... what do you mean? Did you expect it to act like a loop? – juanpa.arrivillaga Aug 04 '18 at 03:12
  • 3
    `with open` is not a loop, `with` is a statement – U13-Forward Aug 04 '18 at 03:13
  • As a side note, `sys.exit` doesn't do anything unless you call it. – abarnert Aug 04 '18 at 03:28
  • 1
    Also, what does "dies" mean here? What actually happens? Does it just exit without a message? Raise an exception? Segfault? And there isn't any code that reads a second line, so where does this dying actually happen? – abarnert Aug 04 '18 at 03:30
  • Possible duplicate of [What is the python keyword "with" used for?](https://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for) – U13-Forward Aug 04 '18 at 03:32

2 Answers2

1

You need to add a loop to iterate over the lines:

import sys

def pause():
    c = input("\nEnter q to quit, anything else to continue") 
    if c.lower() == 'q': 
        sys.exit()

infile = 'ttest.csv'    #  <-- replace with your own file

with open(infile) as f: 
    for line in f:
        print('line = ', line)
        pause()
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
  • Don't suggest `readlines` on code that works perfectly fine without it; just `for line in f:`. There's no reason to read the whole file into memory and build a list. – abarnert Aug 04 '18 at 03:28
0

First of all, with (in this case with open) is not a loop, with is a statement (check out: What is the python keyword "with" used for?) , so try this:

import sys
infile = 'xyz.txt'
def pause():
    c = input("\nEnter q to quit, anything else to continue\n") 
    return c
with open(infile,'r') as f:
    for line in f:
      print("Current line:",line)
      d={'q':sys.exit}
      d.get(pause().lower(), lambda: '')()
sys.exit()

And you're asking the wrong question, readline also works fine with 'with open',

You're title was "in python 3.4, readline works fine alone, but dies in a 'with open' loop. Why?" as mentioned above with is not a loop

U13-Forward
  • 69,221
  • 14
  • 89
  • 114