mercredi 12 février 2020

Why my program does not run the if...else decision tree Python3?

I tried to compare a dictionary value to a string. But the if expression does not work. The program run the statements in if block as well as in else block. I do not understand why. Is there anything wrong in my scripts?

import os
import tarfile
#import urllib.request
from urllib import request as urlrqst


work_path = os.getcwd()
input_control_file = "input_control"
input_control= work_path + "/" + input_control_file

#open control file if file exist
#read setting info
dic = {}
try:
   #if the file does not exist,
   #then it would throw an IOError
   f = open(input_control, 'r')

   #define dictionary/hash table
   for LINE in f:
      LINE = LINE.strip()     #remove leading and trailing whitespace
      lst = LINE.split()      #split string into lists
      lst[0] = lst[0].split(":")[0]
      #dic = {lst[0].strip():lst[1].strip()}    #update dic with the new values
      dic.update({lst[0].strip():lst[1].strip()})    #update dic with the new values
      print(dic[lst[0]])

except IOError:
   # print(os.error) will <class 'OSError'>
   print("Reading file error. File " + input_control + " does not exist.")

#print("keys:",dic.keys())
DATA_URL = dic.get('source') + '/' + dic.get("source_path") + '/' + dic.get("source_file")

def fetch_data(data_url=DATA_URL,data_path=dic.get('source_path')):
   print(data_url,data_path)
   os.makedirs(data_path,exist_ok = True)
   tgz_path = os.path.join(work_path,data_path,dic['source_file'])      #given absolute path
   #urllib.request.urlretrieve(data_url,tgz_path)
   urlrqst.urlretrieve(data_url,tgz_path)
   #if source_type == "tar":   #testing. given tgz file has problems
   if str(dic.get('source_type').strip()) == str("tar").strip():   #testing. given tgz file has problems
      #data_tgz = tarfile.open(tgz_path)
      tf = tarfile.open(tgz_path)
      #data_tgz.extractall(path=data_path)
      tf.extractall()
      unzip = "tar zxvf " + tgz_path
      os.system(unzip)
   else:
      tf = tarfile.open(tgz_path)
   data_tgz.close()

fetch_data()

the dic.get('source_type').strip() = "csv". Ideally, the program should run statements in else. But it run the statements in if and else. Below is the warning message.

Traceback (most recent call last):
  File "wfetchdata.py", line 53, in <module>
    fetch_data()
  File "wfetchdata.py", line 50, in fetch_data
    tf = tarfile.open(tgz_path)
  File "/usr/lib64/python3.6/tarfile.py", line 1576, in open
    raise ReadError("file could not be opened successfully")
tarfile.ReadError: file could not be opened successfully

Aucun commentaire:

Enregistrer un commentaire