如何仅在目录文件名后复制到不带扩展名的目录文件

2024-03-29 12:59:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道我怎么能只按名字复制文件。 例如: 我有

file.png, file2222.png, file.jpeg, file.jpg, file.txt

我可以使用:

for f in files:    
shutil.copy(f, dest)

但是我还必须提供一个扩展名,因为现在计算机不理解文件是什么。它必须具有给定的文件名。文件扩展名

FileNotFoundError: [Errno 2] No such file or directory: '...path/file1'

我可以改进:

for f in files:    
shutil.copy(f + '.txt', dest)

如何复制具有不同扩展名的所有文件“file.*”


Tags: 文件intxtforpng计算机files名字
1条回答
网友
1楼 · 发布于 2024-03-29 12:59:03

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

代码:

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

相关问题 更多 >