标签归档:extract

如何从Python的文件路径中提取文件夹路径?

问题:如何从Python的文件路径中提取文件夹路径?

我只想从完整路径到文件获取文件夹路径。

例如T:\Data\DBDesign\DBDesign_93_v141b.mdb,我想要得到T:\Data\DBDesign(不包括\DBDesign_93_v141b.mdb)。

我已经尝试过这样的事情:

existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\\')[0:-1])
print wkspFldr 

但是它给了我这样的结果:

['T:', 'Data', 'DBDesign']

这不是我需要的结果(为T:\Data\DBDesign)。

关于如何获取文件路径的任何想法?

I would like to get just the folder path from the full path to a file.

For example T:\Data\DBDesign\DBDesign_93_v141b.mdb and I would like to get just T:\Data\DBDesign (excluding the \DBDesign_93_v141b.mdb).

I have tried something like this:

existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\\')[0:-1])
print wkspFldr 

but it gave me a result like this:

['T:', 'Data', 'DBDesign']

which is not the result that I require (being T:\Data\DBDesign).

Any ideas on how I can get the path to my file?


回答 0

您几乎可以使用该split功能了。您只需要加入字符串,如下所示。

>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'

虽然,我建议使用该os.path.dirname函数来执行此操作,但是您只需要传递字符串即可,它将为您完成工作。由于您似乎在Windows上,因此也考虑使用该abspath功能。一个例子:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'

如果要在拆分后同时需要文件名和目录路径,则可以使用os.path.split返回元组的函数,如下所示。

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

You were almost there with your use of the split function. You just needed to join the strings, like follows.

>>> import os
>>> '\\'.join(existGDBPath.split('\\')[0:-1])
'T:\\Data\\DBDesign'

Although, I would recommend using the os.path.dirname function to do this, you just need to pass the string, and it’ll do the work for you. Since, you seem to be on windows, consider using the abspath function too. An example:

>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
'T:\\Data\\DBDesign'

If you want both the file name and the directory path after being split, you can use the os.path.split function which returns a tuple, as follows.

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

回答 1

带有PATHLIB模块(更新后的答案)

人们应该考虑使用pathlib进行新开发。它在适用于Python3.4的stdlib中,但在PyPI上可用于早期版本。该库提供了一种更面向对象的方法来操作路径<opinion>,并且使用更加容易阅读和编程</opinion>

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

使用OS模块

使用os.path模块:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

您可以继续假设,如果您需要进行某种文件名操作,则已经在中实现了os.path。如果没有,您可能仍需要将此模块用作构建模块。

WITH PATHLIB MODULE (UPDATED ANSWER)

One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion> and is much easier read and program with </opinion>.

>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')

WITH OS MODULE

Use the os.path module:

>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr 
'T:\Data\DBDesign'

You can go ahead and assume that if you need to do some sort of filename manipulation it’s already been implemented in os.path. If not, you’ll still probably need to use this module as the building block.


回答 2

内置子模块os.path具有用于该任务的功能。

import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')

The built-in submodule os.path has a function for that very task.

import os
os.path.dirname('T:\Data\DBDesign\DBDesign_93_v141b.mdb')

回答 3

这是代码:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

Here is the code:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

回答 4

这是我的小实用程序帮助程序,用于拆分路径int文件和路径标记:

import os    
# usage: file, path = splitPath(s)
def splitPath(s):
    f = os.path.basename(s)
    p = s[:-(len(f))-1]
    return f, p

Here is my little utility helper for splitting paths int file, path tokens:

import os    
# usage: file, path = splitPath(s)
def splitPath(s):
    f = os.path.basename(s)
    p = s[:-(len(f))-1]
    return f, p

回答 5

任何在ESRI GIS Table字段计算器界面中尝试执行此操作的人都可以使用Python解析器执行此操作:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

以便

\ Users \ me \ Desktop \ New文件夹\ file.txt

变成

\ Users \ me \ Desktop \ New文件夹

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\\".join(!FullFilePathWithFileName!.split("\\")[0:-1])

so that

\Users\me\Desktop\New folder\file.txt

becomes

\Users\me\Desktop\New folder


如何从Python中的字典中提取所有值?

问题:如何从Python中的字典中提取所有值?

我有字典d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}

如何将的所有值提取d到列表中l

I have a dictionary d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}.

How do I extract all of the values of d into a list l?


回答 0

如果你只需要字典的键123使用:your_dict.keys()

如果你只需要在字典中的值-0.3246-0.9185-3985使用:your_dict.values()

如果您想同时使用键和值,请使用:your_dict.items()返回一个元组列表[(key1, value1), (key2, value2), ...]

If you only need the dictionary keys 1, 2, and 3 use: your_dict.keys().

If you only need the dictionary values -0.3246, -0.9185, and -3985 use: your_dict.values().

If you want both keys and values use: your_dict.items() which returns a list of tuples [(key1, value1), (key2, value2), ...].


回答 1

使用 values()

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}

>>> d.values()
<<< [-0.3246, -0.9185, -3985]

Use values()

>>> d = {1:-0.3246, 2:-0.9185, 3:-3985}

>>> d.values()
<<< [-0.3246, -0.9185, -3985]

回答 2

如果需要所有值,请使用以下命令:

dict_name_goes_here.values()

如果需要所有键,请使用以下命令:

dict_name_goes_here.keys()

如果您想要所有项目(键和值),则可以使用以下命令:

dict_name_goes_here.items()

If you want all of the values, use this:

dict_name_goes_here.values()

If you want all of the keys, use this:

dict_name_goes_here.keys()

IF you want all of the items (both keys and values), I would use this:

dict_name_goes_here.items()

回答 3

values()在dict上调用方法。

Call the values() method on the dict.


回答 4

对于Python 3,您需要:

list_of_dict_values = list(dict_name.values())

For Python 3, you need:

list_of_dict_values = list(dict_name.values())

回答 5

对于嵌套字典,字典列表和列出字典的字典,…您可以使用

def get_all_values(d):
    if isinstance(d, dict):
        for v in d.values():
            yield from get_all_values(v)
    elif isinstance(d, list):
        for v in d:
            yield from get_all_values(v)
    else:
        yield d 

一个例子:

d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': 6}]}

list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6]

PS:我爱yield。;-)

For nested dicts, lists of dicts, and dicts of listed dicts, … you can use

def get_all_values(d):
    if isinstance(d, dict):
        for v in d.values():
            yield from get_all_values(v)
    elif isinstance(d, list):
        for v in d:
            yield from get_all_values(v)
    else:
        yield d 

An example:

d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': 6}]}

list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6]

PS: I love yield. ;-)


回答 6

如果需要所有值,请使用以下命令:

dict_name_goes_here.values()

If you want all of the values, use this:

dict_name_goes_here.values()

回答 7

d = <dict>
values = d.values()
d = <dict>
values = d.values()

回答 8

要查看按键:

for key in d.keys():
    print(key)

要获取每个键所引用的值:

for key in d.keys():
    print(d[key])

添加到列表:

for key in d.keys():
    mylist.append(d[key])

To see the keys:

for key in d.keys():
    print(key)

To get the values that each key is referencing:

for key in d.keys():
    print(d[key])

Add to a list:

for key in d.keys():
    mylist.append(d[key])

回答 9

Python的鸭式输入原则上应确定对象可以执行的操作,即其属性和方法。通过查看字典对象,可以尝试猜测它是否具有以下至少一项:dict.keys()dict.values()方法。您应该尝试将这种方法用于将来在运行时会进行类型检查的编程语言,尤其是具有鸭式语言的语言。

Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys() or dict.values() methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.


回答 10

dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()
dictionary_name={key1:value1,key2:value2,key3:value3}
dictionary_name.values()