简体   繁体   English

在Python中获取文件路径的特定部分

[英]Get specific parts of a file path in Python

I have a path string like 我有一个像这样的路径字符串

'/path/eds/vs/accescontrol.dat/d=12520/file1.dat'

Q1: How can I get only accescontrol.dat from the path. 问题1:如何从路径中仅获取accescontrol.dat

Q2: How can I get only /path/eds/vs/accescontrol.dat from the path. 问题2:如何从路径中仅获取/path/eds/vs/accescontrol.dat

You could use regular expressions 您可以使用正则表达式

import re
ma = re.search('/([^/]+\.dat)/d=', path)
print ma.group(1)
import re

url = '/path/eds/vs/accescontrol.dat/d=12520/file1.dat'
match = re.search('^(.+/([^/]+\.dat))[^$]', url)

print match.group(1)
# Outputs /path/eds/vs/accescontrol.dat
print match.group(2)
# Outputs accescontrol.dat

I edited this to work in python2 and to answer both questions (the earlier regex answer above only answers the first of the two) 我对其进行了编辑,以在python2中工作并回答了两个问题(以上较早的regex回答仅回答了两个问题中的第一个)

A simple solution is to use .split() : 一个简单的解决方案是使用.split()

Q1: Q1:

str = '/path/eds/vs/accescontrol.dat/d=12520/file1.dat'
[x for x in str.split('/') if x[-4:] == '.dat']

gives: 得到:

['accescontrol.dat','file1.dat']

A similar trick will answer Q2. 类似的技巧将回答第二季度。

For more advanced file path manipulation I would recommend reading about os.path 对于更高级的文件路径操作,我建议阅读有关os.path
https://docs.python.org/2/library/os.path.html#module-os.path https://docs.python.org/2/library/os.path.html#module-os.path

I would recommend separating each level of folder/file into strings in a list. 我建议将文件夹/文件的每个级别分成列表中的字符串。

path = '/path/eds/vs/accescontrol.dat/d=12520/file1.dat'.split("/")

This makes path = ['path', 'eds', 'vs', 'accescontrol.dat', 'd=12520', 'file1.dat'] 这使得path = ['path', 'eds', 'vs', 'accescontrol.dat', 'd=12520', 'file1.dat']

Then from there, you can access each of the different parts. 然后从那里可以访问每个不同的部分。

Why not this way 为什么不这样

from pathlib import Path
h=r'C:\Users\dj\Pictures\Saved Pictures'
path = Path(h)
print(path.parts)

Path: .
('C:\\', 'Users', 'dj', 'Pictures', 'Saved Pictures')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM