首页 > 解决方案 > 在 Python 中使用 os.rename() 时出现 FileNotFoundError

问题描述

我正在关注这篇文章来重命名文件名,但我在下面遇到错误,我尝试了很多可以在这里找到的潜在解决方案,但没有一个能解决我的问题:

import os
import datetime

current_date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
current_date

os.rename(r'C:\Users\...\xxxx.csv', r'C:\Users\...\xxxx_' + str(current_date) + '.csv'

错误是:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\...\\xxx.csv -> 'C:\\Users\\...\\xxx_2020-04-14 16:43:56.csv'

我该如何解决?

标签: pythondatetimeerror-handlingoperating-system

解决方案


它似乎不喜欢 current_date 的格式

import os
import datetime

current_date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')


old = 'C://path//somefile.csv'
new = 'C://path//somefile'+'new.csv' #str(current_date)+'.csv'
os.rename(old,new)

这对我有用(windows),您不能在文件名中使用某些字符,在这种情况下,它是“:”导致问题,将其更改为“-”应该可以解决它。


推荐阅读