python - 如何在没有扩展名的情况下复制到目录文件 - 仅在名称本身之后
问题描述
我想知道如何仅按名称复制文件。例如:我有
文件.png ,文件2222.png ,文件.jpeg ,文件.jpg ,文件.txt
我可以用:
for f in files:
shutil.copy(f, dest)
但我还必须提供一个扩展名,因为现在计算机不明白该文件是什么。它必须有一个给定的 file_name.file_extension。
FileNotFoundError:[Errno 2] 没有这样的文件或目录:'...path/file1'
我可以改进:
for f in files:
shutil.copy(f + '.txt', dest)
如何复制所有具有不同扩展名的文件'file.*'?
解决方案
您可以尝试使用listdir
and isfile
fromos
模块列出文件夹中的所有文件:
代码:
import os
import shutil
dir = '.'
# get content of the dir
content = os.listdir(dir)
# get only files in dir. file names will be with extensions
list_of_files = [i for i in content if os.path.isfile(i)]
# copy files to new destination
dest = 'dest' # for example
for file in list_of_files:
shutil.copy(os.path.join(dir, file), os.path.join(dest, file))
推荐阅读
- typescript - 将管道应用于控制器中的所有变量出现
- c# - 如何在 C# 中发送电子邮件时修复“发送电子邮件异常失败”?
- micrometer - 千分尺 | 为什么 CompositeMeterRegistry 管理 Set of Registry 而不是 List/LinkedHashSet?
- windows - 安装 Gstreamer 后没有这样的元素 filesrc
- swift - 快速通知操作
- r - 删除数据框中的空值
- c# - 执行 dotnet publish 发布的程序集时找不到依赖项
- asp.net-mvc - 混合 MSAL 和 MVC 表单身份验证
- laravel-backpack - 如何在背包中隐藏字段
- spring - 处理 REST API 调用的顺序