Search code examples
pythonarcpy

Rename directory with constantly changing name


I created a script that is supposed to download some data, then run a few processes. The data source (being ArcGIS Online) always downloads the data as a zip file and when extracted the folder name will be a series of letters and numbers. I noticed that these occasionally change (not entirely sure why). My thought is to run an os.listdir to get the folder name then rename it. Where I run into issues is that the list returns the folder name with brackets and quotes. It returns as ['f29a52b8908242f5b1f32c58b74c063b.gdb'] as the folder name while folder in the file explorer does not have the brackets and quotes. Below is my code and the error I receive.

from zipfile import ZipFile

file_name = "THDNuclearFacilitiesBaseSandboxData.zip"

with ZipFile(file_name) as zip:
    # unzipping all the files
    print("Unzipping "+ file_name)
    zip.extractall("C:/NAPSG/PROJECTS/DHS/THD_Nuclear_Facilities/SCRIPT/CountyDownload/Data")

    print('Unzip Complete')

#removes old zip file
os.remove(file_name)


x = os.listdir("C:/NAPSG/PROJECTS/DHS/THD_Nuclear_Facilities/SCRIPT/CountyDownload/Data")
os.renames(str(x), "Test.gdb")

Output:

FileNotFoundError: [WinError 2] The system cannot find the file specified: "['f29a52b8908242f5b1f32c58b74c063b.gdb']" -> 'Test.gdb'

I'm relatively new to python scripting, so if there is an easier alternative, that would be great as well. Thanks!


Solution

  • os.listdir() returns a list files/objects that are in a folder.

    lists are represented, when printed to the screen, using a set of brackets. The name of each file is a string of characters and strings are represented, when printed to the screen, using quotes.

    So we are seeing a list with a single filename:

    ['f29a52b8908242f5b1f32c58b74c063b.gdb']
    

    To access an item within a list using Python, you can using index notation (which happens to also use brackets to tell Python which item in the list to use by referencing the index or number of the item.

    Python list indexes starting at zero, so to get the first (and in this case only item in the list), you can use x[0].

    x = os.listdir("C:/NAPSG/PROJECTS/DHS/THD_Nuclear_Facilities/SCRIPT/CountyDownload/Data")
    os.renames(x[0], "Test.gdb")
    

    Having said that, I would generally not use x as a variable name in this case... I might write the code a bit differently:

    files = os.listdir("C:/NAPSG/PROJECTS/DHS/THD_Nuclear_Facilities/SCRIPT/CountyDownload/Data")
    os.renames(files[0], "Test.gdb")