NameError: name 'my_gfile' is not defined - glob python

Viewed 26

Trying to create script that can create naming convention for the files on specific folder using glob, but when I run the script I encounter this error, May I know what I need to change on my script?

from datetime import datetime
import os
import glob
import csv

for my_gfile in glob.glob('/root/files/SEN*.csv'):
        print(my_gfile)

date_string = datetime.today().strftime('%Y%m%d"')
new_name = my_gfile + date_string + '.csv'
os.rename(my_gfile, new_name)

Error encounter

NameError: name 'my_gfile' is not defined

1 Answers

Are you sure the for loop was executed succesfully? It seems to me that glob.glob('/root/files/SEN*.csv') is an empty sequence, meaning that the my_gfile variable was never created, meaning that accessing it outside the loop causes the program to crash.

Or maybe you intended to have the last 3 lines in your program inside the loop (and thus executing them for all files and not just the last one)?

Related