简体   繁体   中英

How to use a variable of a IF Block statement in ELIF Block statement in python?

While running this code i am getting error "Local variable "Files" referenced before assignment". I am thinking the scope of variable Files is limited to the IF block. Any suggestions?

import shutil
import os
import logging
import time
import re
timestr = '_'+time.strftime("%Y%m%d-%H%M%S")    
logging.basicConfig(filename = 
"//p4products//nemis2//filehandlerU//ENSUBAPP_log//ENSUBAPP.log"+timestr, level = logging.INFO, 
format = '%(asctime)s:%(levelname)s:%(message)s')
src_dict = "//p4products/nemis2" 
pattern = re.compile ("Ena3s5npf_g") 

def Search_String_File(src_dict,pattern):
   for x in os.listdir(src_dict): 
    print(x)
    if os.path.isfile(os.path.join(src_dict, x)):
        files = os.path.join(src_dict,x)
        strng = open(files) 
        for lines in strng.readlines(): 
            try:
                if re.search(pattern, lines): 
                    print (re.split(r'=', lines))
            except Exception as e:
                    print(e)
                    pass
    elif x != "ENSUBAPP_search.py":
        return Search_String_File(files,pattern)

Search_String_File(src_dict,pattern)      

I am thinking the scope of variable Files is limited to the IF block

That is correct, so move it to a different scope (the loop)

def search_string_file(src_dist, pattern):
    for x in os.listdir(src_dict): 
        print(x)
        child = os.path.join(src_dict,x)
        if os.path.isfile(child):
            with f as open(child):
                for line in f: 
                    try:
                        if re.search(pattern, line): 
                            print (re.split(r'=', line))
                    except Exception as e:
                        print(e)
        elif x != "ENSUBAPP_search.py":
            search_string_file(child, pattern)

Note: You may want to use os.walk or os.glob instead of listdir

Since 'files' is used in both cases (if/else), then you should define it outside of if.

Then you will also save one call to 'join' at the if statement.

Finally, you can use pathlib.Path and save your self some trouble and make a bit more readable code.

def Search_String_File(src_dict,pattern):
   for x in os.listdir(src_dict): 
    print(x)
    if os.path.isfile(os.path.join(src_dict, x)):
        files = os.path.join(src_dict,x)
        strng = open(files) 
        for lines in strng.readlines(): 
            try:
                if re.search(pattern, lines): 
                    print (re.split(r'=', lines))
            except Exception as e:
                    print(e)
                    pass
    elif x != "ENSUBAPP_search.py":
        # declare the files value here, it seems like you should return from here,
        # i can't find any stopping point for this recursion function 
        return "pattern" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM