Python,复制、重命名和运行命令

1 投票
3 回答
1791 浏览
提问于 2025-04-18 15:53

我有一个小任务要为公司完成。

我有多个文件,这些文件的名字都是以swale-加上随机数字开头的。

我想把这些文件复制到一个目录里(请问shutil.copy可以使用通配符吗?)

然后,我想找出最大的那个文件,把它改名为sync.dat,然后再运行一个程序。

我明白这个逻辑,我会用一个循环来逐个完成这些工作,然后再进行下一步,但我不太确定怎么选出最大的文件,或者说怎么选出一个文件,因为当我输入swale*的时候,它肯定会把所有的文件都选上吧?

抱歉我还没有写任何源代码,我还在努力理解这个过程是怎么工作的。

谢谢你们提供的任何帮助。

3 个回答

0

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,不知道该怎么解决。比如,有人可能在使用某个特定的功能时,发现它没有按照预期工作,或者出现了错误信息。这时候,我们就需要去查找资料,看看有没有人遇到过类似的问题,或者有没有解决方案。

在这个过程中,StackOverflow是一个非常有用的资源。它是一个问答网站,专门为程序员提供帮助。用户可以在上面提问,描述他们遇到的问题,其他人则可以回答,分享他们的经验和解决方法。通过这样的互动,大家可以一起学习,找到更好的解决方案。

总之,当你在编程时遇到困难,不妨去看看StackOverflow,那里可能有你需要的答案。

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..
# ...
# ...
1

这个问题的被接受答案在这里提供了一种很不错的、可以在不同系统上使用的文件复制方法,它支持通配符。

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 
0

这可能有效:

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.

注意:这些都没有经过测试,但应该是可以用的。

撰写回答