cambrael
cambrael

Reputation: 1

Python Script doesn't work with certain filenames

I have a script which does the following: If there is a file that ends with 'Kobo.xlsx' in the same directory as the script, it reads the file, makes some changes to it, defines a 'new_filename' from the name of the file, and spits out a new .xlsx with the new filename. Here is the code:

## Get path of Script ##

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
files = os.listdir(dname) 
for file in files:
    if file.endswith('Kobo.xlsx'):
    
        ## Define New Filename ##
    
        filename = os.path.basename(file)
        size = len(filename)
        new_filename = (filename[:size - 9]) + "Sorted.xlsx"

        ## Pandas Things ... ##

    #### Exporting ####

    writer = pd.ExcelWriter(new_filename, engine='xlsxwriter')
    writer.save()
    

Sometimes when I run the script, I get the following error:

    writer = pd.ExcelWriter(new_filename, engine='xlsxwriter')
NameError: name 'new_filename' is not defined

Sometimes when I run the script, I don't. It seems the error only comes up for certain filenames (different directories don't matter). However, If I go through the command prompt to get the new filename, it works in both cases (for the filename that the script worked with, and that the script didn't work with).

How do I avoid the error indefinitely? Thanks in advance - sorry if it's a silly question.

Upvotes: 0

Views: 38

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54698

You don't want to do the write unless you already did the read, so those last two lines need to be indented to be part of the if statement. If the very first file you read does not end in Kobo.xlsx, then you'll try to do the write, but the variable new_filename was never created.

Upvotes: 1

Related Questions