简体   繁体   中英

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

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

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)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM