Python - rename files incrementally based on julian day
<p><strong>Problem:</strong>
I have a bunch of files that were downloaded from an org. Halfway through their data directory the org changed the naming convention (reasons unknown). I am looking to create a script that will take the files in a directory and rename the file the same way, but simply "go back one day". </p>

<p>Here is a sample of how one file is named: <code>org2015365_res_version.asc</code></p>

<p>What I need is logic to only change the year day (<code>2015365</code>) in this case to <code>2015364</code>. This logic needs to span a few years so <code>2015001</code> would be <code>2014365</code>.</p>

<p>I guess I'm not sure this is possible since its not working with the current date so using a module like <code>datetime</code> does not seem applicable.</p>

<p>Partial logic I came up with. I know it is rudimentary at best, but wanted to take a stab at it.</p>

<pre><code># open all files
all_data = glob.glob('/somedir/org*.asc')

# empty array to be appended to
day = []
year = []

# loop through all files
for f in all_data:
    # get first part of string, renders org2015365
    f_split = f.split('_')[0]
    # get only year day - renders 2015365
    year_day = f_split.replace(f_split[:3], '')
    # get only day - renders 365
    days = year_day.replace(year_day[0:4], '')
    # get only year - renders 2015
    day.append(days)
    years = year_day.replace(year_day[4:], '')
    year.append(years)
    # convert to int for easier processing 
    day = [int(i) for i in day]
    year = [int(i) for i in year]

    if day == 001 &amp; year == 2016:
        day = 365
        year = 2015
    elif day == 001 &amp; year == 2015:
        day = 365
        year = 2014
    else:
        day = day - 1
</code></pre>

<p>Apart from the logic above I also came across the function below from <a href="http://stackoverflow.com/questions/225735/batch-renaming-of-files-in-a-directory">this</a> post, I am not sure what would be the best way to combine that with the partial logic above. Thoughts?</p>

<pre><code>import glob
import os


def rename(dir, pattern, titlePattern):
    for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename,
                  os.path.join(dir, titlePattern % title + ext))

rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
</code></pre>

<p>Help me, stackoverflow. You're my only hope.</p>

<p>You can use <a href="https://docs.python.org/3.6/library/datetime.html" rel="nofollow">datetime</a> module:</p>

<pre><code>#First argument - string like 2015365, second argument - format
dt = datetime.datetime.strptime(year_day,'%Y%j')
#Time shift
dt = dt + datetime.timedelta(days=-1)
#Year with shift
nyear = dt.year
#Day in year with shift
nday = dt.timetuple().tm_yday
</code></pre>

python glob