Using PythonWin 2.7.10, I would like to append a date to a bunch of zipfiles in a folder. I've been using the time module which prints the current month, day and year. But, I'm not sure how to append this date to the end of my zipfiles' file name. In this case I've been running tests on the WillCounty_PLSS.zip file, which contains a shapefile.
This script seems to work, but it creates an odd looking file with no content:
import time
import arcpy
from arcpy import env
ws = arcpy.env.workspace = r'\\gisfile\GISstaff\Jared'
current_time = time.strftime("%m%d%Y")
output_name = "WillCounty_PLSS.zip" + current_time
output_file = open(ws + output_name, "w")
print current_time
Here's how the file was named: JaredWillCounty_PLSS.zip02072018
EDIT: What do I need to do to have the look like this: WillCounty_PLSS_02072018.zip?
Solved! Go to Solution.
import os
import time
my_dir = r"D:\myFolder"
current_time = time.strftime("%m%d%Y")
for dirpath, dnames, fnames in os.walk(my_dir):
for file in fnames:
print file
if file.endswith(".zip"):
name, ext = os.path.splitext(file)
new_file_name = "{}{}{}".format(name, current_time, ext)
os.rename(os.path.join(dirpath, file), os.path.join(dirpath, new_file_name))
output_name = "WillCounty_PLSS" + current_time + ".zip"
Matthew,
EDIT: You answered my question, and that worked to name it correctly, but I still have a problem. I wasn't very clear but I actually want a script to put the date on existing zipfiles, this one being one of them in a folder full of them. I'm not sure if the write method is even what I should be doing.
Are you wanting to do more than just rename the existing files? If it is a straight Python exercise, this link has a few different solutions. batch-renaming-of-files-in-a-directory
import os
import time
my_dir = r"D:\myFolder"
current_time = time.strftime("%m%d%Y")
for dirpath, dnames, fnames in os.walk(my_dir):
for file in fnames:
print file
if file.endswith(".zip"):
name, ext = os.path.splitext(file)
new_file_name = "{}{}{}".format(name, current_time, ext)
os.rename(os.path.join(dirpath, file), os.path.join(dirpath, new_file_name))
Blake Terhune's code should let you add a date to the name of zip files in a directory. When I use a date in a filename, I usually format it in year-month-day order as it can be useful when you sort the listing in a file folder.
time.strftime('%y%m%d') # YYMMDD order
Jared,
There was a similar question asked last year, maybe that will help you out.
https://community.esri.com/thread/21496
Regards,
~Shan
Thanks everybody.
While Matthew's renaming link was pretty much what I was looking for I decided to go with Blake's version as it was right here and works great.