Let's break-down your existing code:
if os.path.isfile("file.gz"):
with gzip.GzipFile("file.gz", 'r') as fin:
for line in fin:
The above code would work faster if you made this into a separate function and loaded the file fully first (perform all the I/O in a single operation, loading the data into the memory (much faster), rather than keeping the loop as incrementing the file pointer to read the next line). I/O is slow, always try to get files into a memory structure before doing anything.
if get_new_user is True:
This line would be evaluated every single time the loop runs. We should avoid that.
if datetime.strptime(json.loads(line).get('UpdatedAt'), '%Y-%m-%dT%H:%M:%S.%fZ').date() == (datetime.today()-timedelta(1)).date():
This line executes datetime.today() every single time the loop hits this line. Again, something to avoid by placing the operation result into a variable, before the loop runs.
users.append(json.loads(line))
else:
users.append(json.loads(line))
This is the same line - both sides of the if statement run this exact statement regardless of the result of the date check - meaning the date check is kind of useless - AND the load operation is duplicated/can be separated, right? Perhaps you are missing a line of code? perhaps this is a logic error? It would be helpful to get a comment regarding this.
os.remove("file.gz")
return users
you miss the initial declaration of the users data type. This statement will return either None
or (I'm guessing) a list (because you use .append()
).
With these comments, you should be able to make a piece of code that does something like (this is pseudocode):
function return_file_data(filename)
if file_exists(filename)
data = filename.read_all() #including gunzip
remove(filename)
return data or None
function process_data(data)
users = []
for line in data
users.append(json.loads(line))
return users
function main(filename)
data = return_file_data(filename)
if data
users = process_data(data)
# do something with the users data
if __name__ == "__main__":
filename = get_filename() # I'm sure you do that somewhere?
main(filename)
You'll notice I dropped the datetime comparison AND the get_new_user flag comparison - for reasons mentioned earlier. If you improve your code (as per codereview guidelines), create a new post (with your new code) and reference this post for historical purposes.
Hope this helps!
get_new_user
? \$\endgroup\$