0

I have a basic Python read statement which seems to be derailed by setting what I think it just a variable... but something else is going on I don't understand.

In my code, if I enable line 2, nothing in the 'for' set runs. It's skipped entirely. I'm unclear why that is when it feels like declaring inp should be unrelated to the successive steps?

fhand = open('rubbish.txt')
#inp=fhand.read()

for line in fhand:
    line = line.rstrip()
    if line.startswith('junk'):
        print('found it')
        print(line)
    if not line.startswith('junk'):
        continue

print('end')
print(type(fhand))

2 Answers2

0

Note that when opening files it is always better to use the with statement to ensure that the files are automatically closed when you don't need them anymore even in the even where an error is raised.

If you are going to read the entire file into memory anyways this would be the best solution to get what you want.

with open('rubbish.txt') as fhand:
    inp=fhand.read()

for line in inp.splitlines():
    line = line.rstrip()
    if line.startswith('junk'):
        print('found it')
        print(line)
    if not line.startswith('junk'):
        continue

print('end')
print(type(inp))

Since inp is a string you can loop over it as often as you want, in contrast to a file handle like fhand that behaves more like an iterator.

Maarten Derickx
  • 1,502
  • 1
  • 16
  • 27
  • Thanks for this. I have read up on with and it looks like a clean way to release resources and ensure file closure. Much appreciated. – confusapalooza Jun 05 '21 at 08:44
  • @confusapalooza if answers are useful to please upvote and accept them. It is the preferred way here to show appreciation for answers here. – Maarten Derickx Jun 05 '21 at 09:37
0

because fhand.read() will read all of the file and seek to end of file.

fhand = open('rubbish.txt')
inp=fhand.read()
print(fhand.tell())
for line in fhand:
    line = line.rstrip()
    if line.startswith('junk'):
        print('found it')
        print(line)
    if not line.startswith('junk'):
        continue

print('end')
print(type(fhand))

you can change to this

fhand = open('rubbish.txt')
inp=fhand.read()
fhand.seek(0, 0)
for line in fhand:
    line = line.rstrip()
    if line.startswith('junk'):
        print('found it')
        print(line)
    if not line.startswith('junk'):
        continue

print('end')
print(type(fhand))
ianfun
  • 411
  • 5
  • 10