在python中查找具有特定extension的文件的子路径

2024-06-15 13:35:52 发布

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

我正在尝试在一个文件夹(和子文件夹)中找到我的所有extensionmp4文件,并将它们复制到另一个目录中。我设法找到所有扩展名为mp4的文件,但我没有设法保留这些文件的目录。我的代码如下:

import os
from shutil import copyfile

path = "videos/"
for root, dirs, files in os.walk(path):
    for name in files:
       if name.endswith((".mp4", ".mp4")):
          print(name)
          # copyfile(src, dst)

我想找到名字的路径(对应于我的视频)。我怎么能这么做?你知道吗


Tags: 文件path代码nameinimport目录文件夹
3条回答

使用os.path.join()

import os
from shutil import copyfile

path = "videos/"
for root, dirs, files in os.walk(path):
    for name in files:
       if name.endswith((".mp4", ".mp4")):
          print(os.path.join(root, name))
          # copyfile(src, dst)

虽然认为使用绝对路径更好,但是如果需要相对路径,可以使用os.path.relpath。从os.path.relpath文档

os.path.relpath(path[, start])

Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start.

start defaults to os.curdir.

Availability: Windows, Unix.

New in version 2.6.

为什么不直接使用glob

import glob, shutil
for file in glob.iglob('/foo/*.mp4'): 
    shutil.copy2(file, '/bar/{0}'.format(file))

从上的文档os.步行地址:

dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

所以你的代码应该是这样的:

import os
from shutil import copyfile

path = "videos/"
for root, dirs, files in os.walk(path):
    for name in files:
       if name.endswith((".mp4", ".mp4")):
          print(name)
          src = os.path.join(root, name)
          copyfile(src, dst)

相关问题 更多 >