简体   繁体   中英

Rename file name in python

Im looking to rename a file which is always export(x).csv but the x can be a random number.

Id like to rename it with the date format YYYYMMDDHHMM.csv

import os

old_file = os.path.join("c:\", "export%")

new_file = os.path.join("c:\", "YYYYMMDDHHMM.csv")

os.rename(old_file, new_file)

If you want YYYYMMDDHHMM of the current day, you can use datetime:

s=datetime.today().strftime('%Y%m%d%H%M')

Note that:

  • %Y = Year
  • %m = month
  • %d = day
  • %H = hours
  • %M = Minutes

You can also read this . So, in your code:

new_file = os.path.join("c:/", s+".csv")

Just for example:

from datetime import datetime

s=datetime.today().strftime('%Y%m%d%H%M')
print(s)

will produce:

在此处输入图片说明

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