1

I am new to python and I have a file that I am trying to read.. this file contains many lines and to determine when to stop reading the file I wrote this line:

while True:
    s=file.readline().strip()   # this strip method cuts the '' character presents at the end
    
    # if we reach at the end of the file we'll break the loop
    if s=='':
        break

this is because the file ends with an empty line, so to stop reading the file I used the above code, but the problem is that the file also starts with an empty line so this code will stop it before it reads the remaining lines... how to solve that ?

I know it may sound silly but as I said I am to python and I trying to learn .

James
  • 19
  • 2

4 Answers4

2

You'll be much better off using a with open() construct and an iterator on the file:

with open('myfile.txt') as f:
    for line in f:
        # do whatever with line or line.rstrip()

For example, you can read all the lines in one go into a list:

with open('myfile.txt') as f:
    lines = list(f)

Or, without the trailing '\n':

with open('myfile.txt') as f:
    lines = [s.rstrip() for s in f]
Pierre D
  • 24,012
  • 7
  • 60
  • 96
1

The thing you are looking for is called "end of file" character or EOF

how to find out wether a file is at its eof

mendacium
  • 123
  • 7
0

You can iterate on the opened file

lines = []
with open("some-file.txt") as some_file:
    for line in some_file:
        lines.append(line)
tstr
  • 1,254
  • 20
  • 35
0

Only print Non-Empty lines:

# Opening file 
file = open("text.txt","r")
# Reading lines of file
Lines = file.readlines()
# Using conditional loop as lines are limited
for line in Lines:
    # If line is empty simply pass
    if line.strip() == "":
        pass
    else:
        # Print line
        print(line.strip())

cheers, athrv