1

Hi I have a list of filenames When reading a file, it comes out with an error

Traceback (most recent call last):
  File "test.py", line 229, in <module>
    f = open(i, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'directory_home.json'

How can I skip the error and complete the rest of the files?

code

file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file: 
    f = open(i, 'r')
    data = json.load(f) 
    for i in data['name']:
        print(i)
abdallaEG
  • 103
  • 1
  • 6

3 Answers3

3

Something like this. Note that 'pass' goes to next iteration. 'Continue' would repeat iteration (in this case useless). 'Break' would end iteration.

file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
    try:
        f = open(i, 'r')
        data = json.load(f) 
        for i in data['name']:
            print(i)
        f.colse()
    except FileNotFoundError:
        print("File does not exist")
        pass
Matt Cottrill
  • 152
  • 1
  • 1
  • 15
3

Two options.

Option 1: os.path.isfile

import os
file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file:
    if os.path.isfile(file):
        f = open(i)
        data = json.load(f) 
        for i in data['name']:
            print(i)
    else:
        continue # or whatever you want to do.

Option 2: Exception handling

file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
for i in file: 
    try:
        f = open(i, 'r')
    except FileNotFoundError:
        continue # or whatever
    data = json.load(f) 
    for i in data['name']:
        print(i)
Punker
  • 1,770
  • 9
  • 16
0

You should pur your code in a try-except statement, like this

try:
     file = ["directory_home.json", "directory_ever.json", "home.json", "home.json"]
     for i in file: 
     f = open(i, 'r')
     data = json.load(f) 
     for i in data['name']:
           print(i)
except FileNotFoundError as e:
     # log exception and do whatever you want
     pass

In this way, if your code raises an exception because the file si not present, you are able ti handle It.
Please remember that in the code above, just the exception due to a not existing file si catch. This means that if another exception occurs the code will raise a traceback

Giordano
  • 5,422
  • 3
  • 33
  • 49