【问题标题】:How to rename files after being copied based on creation time?根据创建时间复制后如何重命名文件?
【发布时间】:2022-01-09 09:44:30
【问题描述】:

从用户提供的源和目标复制文件后,需要根据创建时间重命名文件。这些文件有多种扩展类型,在重命名时需要保留,并记录原始文件名。在将文件复制到目标位置后尝试重命名文件时会出现此问题。所有尝试的解决方案都会在回调中创建异常。这里最好的方法是什么?

def filter_copy(self):
    current_dir = self.Source.get()
    destination_dir = self.Destination.get()
    extensions = (['.avi', '.mpg'])

    os.chdir(current_dir)
    for root, dir, files in os.walk('.'):
        for file in files:
            if os.path.splitext(file)[1] in extensions:
                src = os.path.join(root, file)
                time.sleep(0.1)
                logging.info("Copying the file %s..." % file)
                print("Copying the file %s..." % file)
                try:
                    with open('OriginalFilesReceipt.txt', 'w') as f:
                        f.write(file)
                except FileNotFoundError:
                    logging.info("The directory does not exist to create to generate a receipt")
                shutil.copy(src, destination_dir)
    for names in os.listdir('.'):
        t = os.path.getmtime(names)
        v = datetime.datetime.fromtimestamp(t)
        x = v.strftime('%Y%m%d-%H%M%S')
        os.rename(names, x)

【问题讨论】:

  • 您的问题与tkinter 无关,因此您应该创建一个不使用它的 [rme] 并描述您想要的输入和预期输出 - 但大概没有得到 (如果你知道原因,为什么会这样)。

标签: python filesystems


【解决方案1】:

在这里找到了基于 yzhong52 的工作的解决方案:https://gist.github.com/tvdsluijs/1640613a32416b1197fc36b45e7b4999

收到的主要错误应该很明显。工作目录不是目标目录。原问题的解决方案:

os.chdir(destination_dir)
        for names in os.listdir('.'):
            #split into filename and  extension
            filename, extension = os.path.splitext(names)
            if (extension in extensions):
                create_time = os.path.getctime(names)
                format_time = datetime.datetime.fromtimestamp(create_time)
                format_time_string = format_time.strftime("%Y-%m-%d %H.%M.%S")
                newfile = format_time_string + extension

                #if other file with same timestamp
                if(newfile in newfilesDictionary.keys()):
                    index = newfilesDictionary[newfile] + 1
                    newfilesDictionary[newfile] = index
                    newfile = format_time_string + '-' + str(index) + extension
                else:
                    newfilesDictionary[newfile] = 0

                os.rename(names, newfile)
                num_files = num_files + 1
                print(names.rjust(35) + '    =>    ' + newfile.ljust(35))

【讨论】:

    猜你喜欢
    • 2022-11-14
    • 2017-08-04
    • 1970-01-01
    • 2016-11-24
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多