lippo
lippo

Reputation: 33

Error with skipping the first line of a file

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())

Upvotes: 2

Views: 100

Answers (5)

ppwater
ppwater

Reputation: 2277

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())

Upvotes: 1

Tanishq Vyas
Tanishq Vyas

Reputation: 1689

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())

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24280

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())

Upvotes: 2

Red
Red

Reputation: 27577

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!")

Upvotes: 0

mertana
mertana

Reputation: 119

You could wrap it with a try except block:

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

Upvotes: 2

Related Questions