Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为现有文件添加时间戳前缀_Python_Timestamp - Fatal编程技术网

Python:为现有文件添加时间戳前缀

Python:为现有文件添加时间戳前缀,python,timestamp,Python,Timestamp,我正在尝试创建一个python脚本,该脚本将查找现有文件的最后修改的时间戳,并使用该时间戳作为前缀重命名该文件 例如:myfile.txt 2018-07-22至:2018-07-22-myfile.txt 这是我到目前为止所拥有的代码,它还不能解决问题 import os import time dirname = os.getcwd() for item in os.listdir(dirname): if os.path.isfile(os.path.join(dirname,

我正在尝试创建一个python脚本,该脚本将查找现有文件的最后修改的时间戳,并使用该时间戳作为前缀重命名该文件

例如:
myfile.txt 2018-07-22
至:
2018-07-22-myfile.txt

这是我到目前为止所拥有的代码,它还不能解决问题

import os
import time


dirname = os.getcwd()
for item in os.listdir(dirname):
    if os.path.isfile(os.path.join(dirname,item)):
        timeformat = time.strftime('%Y/%m/%d', time.gmtime(os.path.getmtime(item)))
        print ("%s %s" % (timeformat,item))

要重命名该文件,有一个名为的函数,该函数允许您更改该文件的名称

dirname = os.getcwd()
for item in os.listdir(dirname):
    if os.path.isfile(os.path.join(dirname,item)):
        timeformat = time.strftime('%Y-%m-%d-', time.gmtime(os.path.getmtime(item)))
        new_name = '%s %s' % (timeformat, item)
        os.rename(item, new_name)

它在解决问题方面有哪些不足之处?是否发生了任何错误?你从来没有在你的帖子中问过其他人要回答的问题。你如何像在输出中看到的那样重命名文件?我让它以我想要的方式打印到屏幕上,但我不知道如何实际重命名它们。
dirname = os.getcwd()
for item in os.listdir(dirname):
    if os.path.isfile(os.path.join(dirname,item)):
        timeformat = time.strftime('%Y-%m-%d-', time.gmtime(os.path.getmtime(item)))
        new_name = '%s %s' % (timeformat, item)
        os.rename(item, new_name)