Total python beginner here.
I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.
I have to break out of looping, immediately after the match is found, to avoid needless looping.
Here is the code:
def DateZoneCity_downloaded_previously(Order_Date,ZoneCity): # function to check if a given DateZoneCity
# combination had already been completely downloaded
string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
with open(Record_File) as download_status:
DateZoneCity_exists = False
for line in download_status:
if string_to_match in line:
DateZoneCity_exists = True # if match found, then set "DateZoneCity_exists" to True
break # and break out from the [for line in download_status:] loop
if DateZoneCity_exists: return True
download_status.close()
I am searching for a more concise, pythonic way to structure the code. Is there anything I can do to make this better? Somehow to eliminate the need for "DateZoneCity_exists" and the second If statement?
download_status.closeddoing at the end?download_statuswill be automatically closed when leaving thewithblock — that's the point of using thewithblock.