在Python中使用时间戳重命名将文件移动到子目录

2024-05-04 11:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将一个文件复制到一个子目录,其名称更改为name_timestamp(通过附加时间戳)。你知道吗

我正在csv文件上使用一个副本method,一旦复制完成,我需要将csv文件移动到一个子目录并将其重命名为CSV_timestamp。你知道吗

下面是示例代码。有人能帮我或建议我怎么做吗?你知道吗

 import os, shutil, time

 if not os.path.exists(dirName):
    os.mkdir(dirName)
    print("Directory " , dirName ,  " Created ")
 else:    
    print("Directory " , dirName ,  " already exists")

def copyFile(src, dest):
    try:
        shutil.copy(src, dest)
    # eg. src and dest are the same file
    except shutil.Error as e:
        print('Error: %s' % e)
    # eg. source or destination doesn't exist
    except IOError as e:
        print('Error: %s' % e.strerror)

os.rename("path/to/current/age.csv", "path/to/new/destination/for/age.csv")
shutil.move("path/to/current/age.csv", "path/to/new/destination/for/age.csv")

Tags: 文件csvtopathsrcageosexists
3条回答

你可以用操作系统重命名()仪表

import time
timestamp_name=int(time.time())
os.rename('path/to/file/name.text','path/to/file/'+timestamp_name+'.txt)

它应该很简单,只要在完成时将目标路径设置为您想要的任何目录。你知道吗

例如,假设您的文件位于users/foo/bar中/我的文件.csv(这将是您的src路径)。假设您希望该文件的副本位于users/mydocuments/bar/foo中/我的新文件.csv(这将是您的dest路径)。你知道吗

你需要做的就是:

import shutil
import os
src = 'users/foo/bar/myfile.csv'
tstamp = os.path.getmtime(path)
dest = 'users/mydocuments/bar/foo/mynewfile' + tstamp + '.csv'
shutil.move(src,dest)

按照您的方法(使用检查目录是否存在的函数等),您可以执行以下操作:

import os
import shutil
from time import gmtime, strftime

def copyFile(old_path, new_directory):
   # check if the directory already exists
    if not os.path.exists(new_directory):
        os.mkdir(new_directory)
        print(f"Directory {new_directory} Created.")
    else:    
        print(f"Directory {new_directory} already exists.")

    # create new path from new_directory, the filename and the timestamp
    new_path = new_directory + old_path.split("/")[len(old_path)-1].split(".")[0] + strftime("%Y_%m_%d", gmtime()) + ".csv"

    # copy the file to the new path
    try:
        shutil.copy(old_path, new_path)
    # eg. src and dest are the same file
    except shutil.Error as e:
        print(f"Error: {e}")
    # eg. source or destination doesn't exist
    except IOError as e:
        print(f"Error: {e.strerror}")

old_path = '/path/to/directory/file.csv'
new_directory = '/path/to/new/directory/'

copyFile(old_path, new_directory)

请注意

  1. 从python3.6开始,可以使用f字符串更容易地在字符串中包含变量。你知道吗
  2. 我不清楚你在找什么样的时间戳。 这种方法将给您一个YYYY_MM_DD格式的戳记 但是你可以很容易地改变,看到了吗 documentationtime包上。你知道吗
  3. 使用shutil.copy之后,您不再需要shutil.move,因为 第一个已复制了您的文件并将其保存到目标 路径。你知道吗

相关问题 更多 >