Postingan lainnya
selalu keluar error UnboundLocalError: local variable 'ori_code' referenced before assignment
import logging.config
import yaml
import ConfigParser
import glob,sys,os
IN_DIR = 'D:\\DATA\\OUT\\*.hl7'
config = ConfigParser.ConfigParser()
config.read('order_file.ini')
def main():
logging.debug('main() IN_DIR[%s]' % IN_DIR)
for hl7_file in glob.glob(IN_DIR):
logging.info(hl7_file)
with open(hl7_file) as f_open:
f_content = f_open.readlines()
logging.debug(f_content)
for l in f_content:
if l[:3] == 'PV1':
logging.info('PV1')
l_sp = l.split('|')
logging.info(l_sp[3])
ori_code = l_sp[3]
#ori_code = l_sp[3].split('.')[0]
#ori_name = l_sp[3].split('^')[3]
#logging.info('ori_code [%s] ori_name[%s]' % (ori_code,ori_name))
logging.info('ori_code [%s]' % (ori_code))
if ori_code == '010108': #FOLDER MCU
f_name = os.path.basename(hl7_file)
out_fname = OUT_DIR_RUTIN+f_name
logging.info('to [%s]' % (out_fname))
os.rename(hl7_file,out_fname)
elif ori_code == '010113': #FOLDER RUTIN
f_name = os.path.basename(hl7_file)
out_fname = OUT_DIR_MCU+f_name
logging.info('to [%s]' % (out_fname))
os.rename(hl7_file,out_fname)
else:
f_name = os.path.basename(hl7_file)
out_fname = OUT_DIR_OTHERS+f_name
logging.info('to [%s]' % (out_fname))
os.rename(hl7_file,out_fname)
if __name__ == "__main__":
with open('order_file.yaml', 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
main()
0
1 Jawaban:
UnboundLocalError: local variable 'ori_code' terjadi karena ori_code belum di definisikan sebelumnya,,, jadi tetep harus di identifikasi dulu walau dengan NONE atau false (buat pv1 nya)
def main():
logging.debug('main() IN_DIR[%s]' % IN_DIR)
for hl7_file in glob.glob(IN_DIR):
logging.info(hl7_file)
ori_code = None # Inisialisasi ori_code
pv1_found = False # Flag untuk menandai apakah PV1 ditemukan
with open(hl7_file) as f_open:
f_content = f_open.readlines()
logging.debug(f_content)
for l in f_content:
if l[:3] == 'PV1':
logging.info('PV1')
l_sp = l.split('|')
try:
ori_code = l_sp[3]
logging.info(ori_code)
pv1_found = True
break # Keluar dari loop setelah menemukan PV1
except IndexError:
logging.warning("PV1 line doesn't have expected number of elements")
if not pv1_found:
logging.warning("No PV1 line found in file: %s" % hl7_file)
continue # Lanjut ke file berikutnya
if ori_code is None:
logging.warning("Unable to extract ori_code from file: %s" % hl7_file)
continue # Lanjut ke file berikutnya
logging.info('ori_code [%s]' % ori_code)
f_name = os.path.basename(hl7_file)
if ori_code == '010108': # FOLDER MCU
out_fname = OUT_DIR_RUTIN + f_name
elif ori_code == '010113': # FOLDER RUTIN
out_fname = OUT_DIR_MCU + f_name
else:
out_fname = OUT_DIR_OTHERS + f_name
logging.info('to [%s]' % out_fname)
os.rename(hl7_file, out_fname)
1
Tanggapan
ini make sense +1