Python解析路径列表

时间:2012-08-13 21:03:39

标签: python parsing

我在.txt文件中有一个路径列表,我正在尝试使用python解析路径名中的一个文件夹。

9999\New_folder\A\23818\files\  
9999\New_folder\A\18283_HO\files\  
...

我感兴趣的是在9999\New_folder\A\\files\之间拉动字符串,以便我最终得到:

23818  
18283_HO

任何帮助将不胜感激!

编辑:非常感谢大家!根据您的输入提出以下代码。

input_text = open('C:\\Python\\textintolist\\Document1.txt', 'r')
output_text = open('output.txt', 'w')

paths =[]


for line in input_text:
    paths.append(line)

for path in paths:
        output_text.write(str(path.split('\\')[3])+"\n")

4 个答案:

答案 0 :(得分:1)

>>> s = '9999\\New_folder\\A\\23818\\files\\'
>>> s.split('9999\\New_folder\\A\\')[1].split('\\')[0]
'23818'

答案 1 :(得分:0)

有很多解决方案。 如果所有路径都是9999 \ New_folder \ A#number#\ files \那么你可以通过查找第三个最后一个和最后一个“\”来获取一个子字符串。 您可以使用rfind()(http://docs.python.org/library/string.html#string.rfind)

来完成此操作

另一种更通用的方法是使用正则表达式。 http://docs.python.org/library/re.html

答案 2 :(得分:0)

如果您的路径始终采用以下格式:

>>> paths
['9999\\New_folder\\A\\23818\\files\\', '9999\\New_folder\\A\\18283_HO\\files']
>>> for path in paths:
...     print path.split('\\')[3]
...
23818
18283_HO

答案 3 :(得分:0)

#sm.th. like this should work:
file_handler = open("file path")
for line in file_handler:   
    re.search(r'\\(.[^\\]+)\\files', line).groups(0)[0]