python获取绝对路径_python-获取目录中所有文件的绝对路径

python-获取目录中所有文件的绝对路径

如何获取目录中所有文件的绝对路径,这些目录在Python中可能具有许多子文件夹?

我知道os.walk()递归地为我提供了目录和文件列表,但这似乎并不能为我提供所需的信息。

8个解决方案

53 votes

os.path.abspath确保路径是绝对的。 使用以下帮助器功能:

import os

def absoluteFilePaths(directory):

for dirpath,_,filenames in os.walk(directory):

for f in filenames:

yield os.path.abspath(os.path.join(dirpath, f))

phihag answered 2020-02-21T12:25:41Z

15 votes

如果给os.walk提供的参数是绝对的,则在迭代过程中产生的根目录名称也将是绝对的。 因此,您只需要使用文件名将它们加入:

import os

for root, dirs, files in os.walk(os.path.abspath("../path/to/dir/")):

for file in files:

print(os.path.join(root, file))

wim answered 2020-02-21T12:26:02Z

9 votes

尝试:

import os

for root, dirs, files in os.walk('.'):

for file in files:

p=os.path.join(root,file)

print p

print os.path.abspath(p)

print

the wolf answered 2020-02-21T12:26:22Z

7 votes

您可以使用os.path.abspath()将相对路径转换为绝对路径:

file_paths = []

for folder, subs, files in os.walk(rootdir):

for filename in files:

file_paths.append(os.path.abspath(os.path.join(folder, filename)))

Blender answered 2020-02-21T12:26:43Z

6 votes

如果您使用Python 3.4或更高版本,则可以使用pathlib(如果您使用的是旧版本的Python,则可以使用第三方backport):

import pathlib

for filepath in pathlib.Path(directory).glob('**/*'):

print(filepath.absolute())

MSeifert answered 2020-02-21T12:27:03Z

0 votes

我想保留子目录的详细信息,而不要保留文件,只希望其中包含一个xml文件的子目录。 我可以这样:

for rootDirectory, subDirectories, files in os.walk(eventDirectory):

for subDirectory in subDirectories:

absSubDir = os.path.join(rootDirectory, subDirectory)

if len(glob.glob(os.path.join(absSubDir, "*.xml"))) == 1:

print "Parsing information in " + absSubDir

Eamonn Kenny answered 2020-02-21T12:27:23Z

0 votes

from glob import glob

def absolute_file_paths(directory):

return glob(join(directory, "**"))

AmjadHD answered 2020-02-21T12:27:39Z

0 votes

for root, directories, filenames in os.walk(directory):

for directory in directories:

print os.path.join(root, directory)

for filename in filenames:

if filename.endswith(".JPG"):

print filename

print os.path.join(root,filename)

Robert A answered 2020-02-21T12:27:54Z

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值