python - 在Python中使用os.rename()时出现FileNotFoundError

标签 python datetime error-handling operating-system

我正在按照这个post重命名文件名,但是在下面出现错误,我尝试了很多可能的解决方案,但都无法解决我的问题:

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'

我该如何解决?

最佳答案

似乎不喜欢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),您不能在文件名中使用某些字符,在这种情况下,这是导致问题的“:”,将其更改为“-”即可解决。

关于python - 在Python中使用os.rename()时出现FileNotFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61212379/

相关文章:

python - 防止 input() 为字母字符以外的任何内容

vb.net - MVC 3 错误处理的正确编码示例

python - KeyError:Python 字典键中的反斜杠

python - 通过 Matlab 的 system() 通过 shell 脚本调用 python 脚本会导致奇怪的错误

Python 文件上传小部件不工作,它没有在 jupyter notebook 中显示上传按钮

Java 8 : Difference between two LocalDateTime in multiple units

python - 如何在 python 中将 J2000 时间转换为 UTC?

c# - 日期时间-新的一天开始于 3 :00 am

c# - 明确指定模型数据类型 MVC/C#

oracle - 无法引发应用程序错误消息