简体   繁体   中英

Python: Nested loops for renaming files with julian dates

I have ~30,000 daily temperature rasters (.asc) from 1971-2070 which need to be renamed. They are currently named as follows: tasmax_0.asc, tasmax_1.asc,....,tasmax_32767.asc.

I need to rename them with the julian date and year (ie, tasmax_1_1971.asc, tasmax_2_1971.asc,....,tasmax_365_2070.asc).

I know I need to use a nested loop with different counters: a julian day counter (which needs to be reset at the start of each year), and a year counter. I get easily confused with nested loops, especially where leap years would have 366 days instead of 365 and I have to reset the julian day counter every year.

I am using python 2.7

Any help with wrapping my head around writing this script would be greatly appreciated!

Thanks in advance!

Perhaps something like this is what you are looking for:

import os
filex = 0
year = 1971
while filex < 32768:
    if (( year%400 == 0)or (( year%4 == 0 ) and ( year%100 != 0))):
        days = 366
    else:
        days = 365
    current_day = 1
    while current_day <= days:
        os.rename(("tasmax_" + str(filex) + ".asc"),(("tasmax_" + str(current_day) + str(year) + ".asc")))
        current_day = current_day + 1
        filex = filex + 1
    year = year + 1

a counter for the file number, the days in the year, the current day, and the current year.

to rename the file im using

os.rename(oldfilename, newfilename)

but use whatever you would prefer.

This example just prints out 1_1971 , 2_1971 , etc.

from datetime import date, timedelta

day = date(1971, 1, 1) #1 Jan 1971
step = timedelta(1)    #1 day
curr_year = day.year
count = 1

while day.year <= 2070:
    print("{}_{}".format(count, curr_year))
    day += step
    count += 1
    if day.year != curr_year:
        count = 1
        curr_year = day.year

You can use Python's datetime module.

import os
import datetime

start_date = datetime.datetime(1971, 1, 1) # January 1, 1971

for fname in os.listdir("date_folder"): # Iterate through filenames
    num_days = fname.split("_")[1] # Check number of days from start
    cur_date = start_date + datetime.timedelta(days=num_days) # Add number of days to start
    os.rename(fname, "tasmax_{0}_{1}".format(cur_date.day, cur_date.year)) # Reformat filename

This assumes that all the files are in a directory by themselves.

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