【问题标题】:Python, Copy, Rename and run CommandsPython,复制,重命名和运行命令
【发布时间】:2014-08-04 08:29:12
【问题描述】:

我的公司有一个小任务

我有多个以 swale-randomnumber 开头的文件

然后我想复制到某个目录(shutil.copy 是否允许通配符?)

无论如何,我想选择最大的文件并将其重命名为sync.dat,然后运行一个程序。

我明白了逻辑,我将使用一个循环来完成每个单独的工作,然后继续进行下一个工作,但我不确定如何选择一个最大的文件或一个文件,因为当我输入 swale* 肯定会选择它们吗?

抱歉,我还没有编写任何源代码,我仍在努力弄清楚它是如何工作的。

感谢您提供的任何帮助

【问题讨论】:

  • 堆栈溢出不是代码开发服务——但我会给你一些提示:据我所知,shutil 不支持通配符。通配符扩展由命令行 shell 完成。您将需要使用 glob 模块进行通配符匹配,并在进行复制之前识别您需要复制的文件。您将需要使用 os.path.size 来选择最大的文件。

标签: python copy rename move


【解决方案1】:

this question 的公认答案提出了一个很好的可移植的文件复制实现,支持通配符:

from glob import iglob
from shutil import copy
from os.path import join

def copy_files(src_glob, dst_folder):
    for fname in iglob(src_glob):
        copy(fname, join(dst_folder, fname))

如果要比较文件大小,可以使用以下任一函数:

import os
os.path.getsize(path)
os.stat(path).st_size 

【讨论】:

    【解决方案2】:

    这可能有效:

    import os.path
    import glob
    import shutil
    
    source = "My Source Path" # Replace these variables with the appropriate data
    dest = "My Dest Path"
    command = "My command"
    
    # Find the files that need to be copied
    files = glob.glob(os.path.join(source, "swale-*"))
    
    # Copy the files to the destination
    for file in files:
         shutil.copy(os.path.join(source, "swale-*"), dest)
    
    # Create a sorted list of files - using the file sizes
    # biggest first, and then use the 1st item 
    biggest = sorted([file for file in files], 
            cmp=lambda x,y : cmp(x,y), 
            key=lambda x: os.path.size( os.path.join( dest, x)),  reverse = True)[0]
    
    # Rename that biggest file to swale.dat
    shutil.move( os.path.join(dest,biggest), os.path.join(dest,"swale.date") )
    
    # Run the command 
    os.system( command ) 
    # Only use os.system if you know your command is completely secure and you don't need the output. Use the popen module if you need more security and need the output.
    

    注意:这些都没有经过测试 - 但它应该可以工作

    【讨论】:

      【解决方案3】:
      from os import *
      from os.path import *
      
      directory = '/your/directory/'
      
      # You now have list of files in directory that starts with "swale-"
      fileList = [join(directory,f) for f in listdir(directory) if f.startswith("swale-") and isfile(join(directory,f))]
      
      # Order it by file size - from big to small
      fileList.sort(key=getsize, reverse=True)
      
      # First file in array is biggest
      biggestFile = fileList[0]
      
      # Do whatever you want with this files - using shutil.*, os.*, or anything else..
      # ...
      # ...
      

      【讨论】:

        猜你喜欢
        • 2014-07-18
        • 2013-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-04
        • 2021-09-18
        • 2012-02-12
        • 2021-06-08
        相关资源
        最近更新 更多