1

I have a list of names within a file.

Each time my program turns to one name from the list, and extracts data.

The problem is that sometimes some of the name(s) are not available (temporarily and randomaly).

A name that was unavailable yesterday, will be available today. but, another name that was available yesterday, will not be available today).

As soon as the program reach unavailable name then the program gets stuck.

What can you do for the program to skip a name(s) that is not available at this moment? so that the program always work and not get stuck.

Hope i am clear... :)

my list:

Name_1

Name_2

Name_3

Name_4

Name_5

my program:

with open('D:\My_Path.txt', 'r') as fp:
    Names = [line.rstrip('\n') for line in fp.readlines()] 

for Name in (Names):
    '''Do something'''
Mypel
  • 149
  • 1
  • 1
  • 10
  • what error do you get if the program gets stuck? – onno Oct 30 '18 at 10:10
  • @onno, i got this error: UnboundLocalError: local variable 'path' referenced before assignment – Mypel Oct 30 '18 at 10:19
  • Add that '''Do something''' part please, otherwise you should go ahead with the try/except statement. – Kian Oct 30 '18 at 10:43
  • @Ssein, "Do something" is some mathematical calculations only. the error came before the calculations. I tried to use try/except as anno say, but still got the same error. each time (OTHER DAY), the program stuck at other name. – Mypel Oct 30 '18 at 10:54
  • Where is the variable `path` in your code? – Guimoute Oct 30 '18 at 11:03
  • @Mypel: Can you add your code to your question? Maybe we can see why the try/except statement does not work – onno Oct 30 '18 at 11:20
  • 1
    @onno. Thanks to you, it works great !!! – Mypel Oct 30 '18 at 11:22

1 Answers1

2

use a try / except statement with the error you get as an exception.

with open('D:\My_Path.txt', 'r') as fp:
    Names = [line.rstrip('\n') for line in fp.readlines()] 

for Name in (Names):
    try:
        '''Do something'''
    except UnboundLocalError:
        print('%s not available'%Name)

EDIT: I don't know what '''Do something''' is. Apparently it gives an UnboundLocalError if the Name does not exist. It is good practice to look exactly which statement cause this error and put this exception in the try/except block. See also this post: Why is "except: pass" a bad programming practice?

For general information about a try/except block see: https://docs.python.org/3/tutorial/errors.html

onno
  • 969
  • 5
  • 9