【问题标题】:Rename/Backup old directory in python在python中重命名/备份旧目录
【发布时间】:2016-12-17 13:03:15
【问题描述】:

我有一个定期创建新目录的脚本。我想检查它是否已经存在,如果存在,请将现有文件夹移动到备份中。我的第一次迭代是

if os.path.isdir(destination_path):
   os.rename(destination_path,destination_path + '_old')

但是,如果已经备份了一个,它显然会崩溃。我想做的是找到与destination_path 匹配的目录数量,并将该数字附加为版本号。

if os.path.isdir(destination_path):
   n = get_num_folders_like(destination_path)
   os.rename(destination_path,destination_path + str(n))

我只是不确定如何制作这样一个假设函数。我认为 fnmatch 可能有效,但我无法正确使用语法。

【问题讨论】:

  • 备份目录的数量有限制吗?

标签: python directory rename


【解决方案1】:

根据给出的更一般的答案,我最终为我的具体案例使用了更精简的东西

if os.path.isdir(destination_path):
    n = len(glob.glob(destination_path + '*'))
    os.rename(destination_path, destination_path + '_' + str(n))

【讨论】:

    【解决方案2】:

    如果您需要将旧目录移到一边,可以很容易地重新编号,方法是列出所有同名目录,然后通过从匹配名称中提取数字最大值来选择最后一个。

    可以使用glob module 来列出目录;它将列表文件与fnmatch 模块结合起来进行过滤:

     import glob
    
    if os.path.isdir(destination_path):
         # match all paths starting with the destination name, plus at least
         # an underscore and one digit.
         backups = glob.glob(destination_path + '_[0_9]*')
         def extract_number(path):
             try:
                 # assume everything after `_` is a number
                 return int(path.rpartition('_')[-1])
             except ValueError:
                 # not everything was a number, skip this directory
                 return None
    
         backup_numbers = (extract__number(b) for b in backups)
         try:
             next_backup = max(filter(None, backup_numbers)) + 1
         except ValueError:
             # no backup directories
             next_backup = 1
    
    os.rename(destination_path,destination_path + '_{:d}'.format(next_backup))
    

    我假设您不担心这里的比赛条件。

    【讨论】:

    • 为什么你认为这种方法会失败?你担心比赛条件吗?每次运行时,它都会检查类似的文件并移动当前为destination_path 的文件。此过程是手动触发的,因此竞争条件不会成为问题。我不明白你的例子。创建一个独特且可解释的“文件名”是我要解决的问题。
    • @Keith:对,那我误会你了;你说过如果已经备份了它显然会崩溃。我将其解释为如果一个同时被备份,因为在这种情况下,您的代码确实会引发异常,因为目标目录已经存在。
    • @Keith:现在回答了“根据现有目录重新编号”的问题。
    猜你喜欢
    • 2014-08-08
    • 2018-05-08
    • 2015-12-03
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 2012-03-13
    • 2017-02-04
    • 1970-01-01
    相关资源
    最近更新 更多