python统计指定目录中文件个数和文件名_python在一个目录中文件名的数量最多

使用re:import re

filenames = [

'file1.jpg',

'file2.jpg',

'file3.jpg',

'file4.jpg',

'fileA.jpg',

]

### We'll match on a general pattern of any character before a number + '.jpg'

### Then, we'll look for a file with that number in its name and return the result

### Note: We're grouping the number with parenthesis, so we have to extract that with each iteration.

### We also skip over non-matching results with teh conditional 'if'

### Since a list is returned, we can unpack that by calling index zero.

max_file = [file for file in filenames if max([re.match(r'.*(\d+)\.jpg', i).group(1) for i in filenames if re.match(r'.*(\d+)\.jpg', i)]) in file][0]

print(f'The file with the maximum number is: {max_file}')

输出:

The file with the maximum number is: file4.jpg

注意:无论文件名中的数字前是否有字母,这都是有效的,因此您可以(几乎)随意命名文件。在

*第二个解决方案:使用创建日期。*

这与第一个类似,但我们将使用操作系统模块并迭代目录,返回一个具有最新创建日期的文件:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Python的os和shutil模块来实现这个任务。下面是一个示例代码: ```python import os import shutil def get_files_with_specific_name(directory, file_name, output_directory): # 获取目录下的所有文件夹 subdirectories = [name for name in os.listdir(directory) if os.path.isdir(os.path.join(directory, name))] for subdirectory in subdirectories: # 构建当前子文件夹的完整路径 subdirectory_path = os.path.join(directory, subdirectory) # 获取当前子文件夹下的所有文件 files = [name for name in os.listdir(subdirectory_path) if os.path.isfile(os.path.join(subdirectory_path, name))] # 寻找指定文件名文件并复制到输出目录 for file in files: if file == file_name: output_subdirectory = os.path.join(output_directory, subdirectory) os.makedirs(output_subdirectory, exist_ok=True) # 创建输出子文件夹 source_file = os.path.join(subdirectory_path, file) destination_file = os.path.join(output_subdirectory, file) shutil.copy(source_file, destination_file) print(f"已复制文件: {file} 到目录: {output_subdirectory}") # 指定目录和输出目录 directory = 'path/to/directory' output_directory = 'path/to/output_directory' file_name = 'example.txt' # 指定文件名 # 调用函数获取指定文件名文件并保存到指定文件夹 get_files_with_specific_name(directory, file_name, output_directory) ``` 在上面的示例代码,你需要将`directory`替换为你想要搜索的目录路径,将`output_directory`替换为你想要保存指定文件名文件目录路径,将`file_name`替换为你想要获取的特定文件名。代码会遍历指定目录下的所有文件夹,并将符合指定文件名文件复制到指定的输出目录的子文件夹。 请确保在运行代码之前已经安装了必要的模块(os、shutil),并将目录路径和文件名替换为你自己的实际路径和文件名

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值