简体   繁体   中英

How to rename multiple netCDF files in a folder with dates inside these using python script?

I have 28 files for example:-

File -> day01.nc inside file:-

| lat | lon | date      |
| --- | --- | --------  |
| 7   | 68  | 2021-02-01|
| 7   | 69  | 2021-02-01|

File -> day02.nc inside file:-

| lat | lon | date      |
| --- | --- | --------  |
| 7   | 68  | 2021-02-02|
| 7   | 69  | 2021-02-02|

File -> day28.nc inside file:-

| lat | lon | date      |
| --- | --- | --------  |
| 7   | 68  | 2021-02-28|
| 7   | 69  | 2021-02-28|

I want to convert their name according to date format like temp_ind20210201.nc , temp_ind20210202.nc ,..., temp_ind20210328.nc using python script.

Note:- In day01.nc the date format inside that file is like 2021-02-01 and so on. I was trying:-

DATA_DIR = 'data'
today = datetime.datetime.now()
offset_1day = datetime.timedelta(days=1)
re_number = re.compile('day(\d{,2})\.nc')

for fname in glob.glob(DATA_DIR + "/*.nc"):
      number_string = re_number.search(fname)
if not number_string:
      continue
   number_of_days = int(number_string.group(1))
   str_timestamp = (today + (number_of_days - 1) * offset_1day).strftime("%Y%m%d")
   new_fname = f"{DATA_DIR}/temp_ind{_str_timestamp}.nc"
   print(f'{fname} -> {new_fname}')
   os.rename(fname, new_fname)

Based on the question and comments beneath it, you want to be able to extract the first date in a NetCDF file and use that to generate a new file name for that file. The following should work, but might need tweaking, depending on how time is formatted:

import xarray as xr
ds = xr.open_dataset("infile.nc")
"temp_ind" + ds.time[0].values.astype("str")[0:10].replace("-","") + ".nc"

I would probably do this in a loop from the command line in bash. I pipe the output from CDO to awk, in case any file has more than one date, this will ensure that the file is renamed to the first date in the file

for file in day*.nc ; do 
   mv $file temp_ind`cdo -s showdate $file | awk '{print $1}'`.nc
done 

note that CDO outputs a date with hyphens yyyy-mm-dd, so you get a filename with hyphens included - you can remove those with a second pipe to sed if you don't like that.

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