首页 > 解决方案 > 如何在没有扩展名的情况下复制到目录文件 - 仅在名称本身之后

问题描述

我想知道如何仅按名称复制文件。例如:我有

文件.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.*'?

标签: pythonfilecopy

解决方案


您可以尝试使用listdirand isfilefromos模块列出文件夹中的所有文件:

代码:

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))

推荐阅读