Error with skipping the first line of a file

Viewed 75

With the command next(a_file), I can skip the first line of a file but only if there is actually a line. If there is nothing in the file at the time of the command I get an error. How can I avoid this problem?

Example for error:

a_file = open("helloo.txt") 
next(a_file) 
print(a_file.read())
5 Answers

Just use a try: except block. You want to catch only the StopIteration exception, so that any other (FileNotFoundError,...) doesn't get caught here:

a_file = open("helloo.txt") 
try:
    next(a_file)
except StopIteration:
    print("Empty file")
    # or just
    #pass

print(a_file.read())

You could wrap it with a try except block:

try:
    next(a_file)
except StopIteration:
    # handle the exception

You can simply make use of try-except block in python in order to detect if there is any error occurring while calling the next() method. In case any error occurs, which in your case will be StopIteration, we execute the except block and thus the program continues smoothly.


a_file = open("helloo.txt") 

try:
    next(a_file) 
except StopIteration:
    print("File is empty.")
    
print(a_file.read())

Check if the file is empty and if not, do next():

import os

a_file = open("helloo.txt")
if os.stat("helloo.txt").st_size != 0:
    next(a_file) 
print(a_file.read())
a_file.close()

Or you can use try except like this:

a_file = open("helloo.txt") 
try:
    next(a_file)
except StopIteration:
    pass

print(a_file.read())

It is a bad practice to assign a open call to a variable via the = operator. Instead, use with:

with open("usernames.txt") as a_file:
    try:
        next(a_file)
        print(a_file.read())
    except StopIteration:
        print("Empty")

I'd also like to introduce you to the finally statement; it only comes after both try and except are used in a block:

with open("usernames.txt") as a_file:
    try:
        next(a_file)
        print(a_file.read())
    except StopIteration:
        print("Empty")
    finally:
        print("End!")
Related