2012-08-13 112 views
0

我有一個.txt文件中的路徑列表,我試圖用python解析出路徑名中的一個文件夾。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") 
+0

使用正則表達式[正則表達式(http://docs.python.org/howto/regex.html) – profitehlolz 2012-08-13 21:12:38

回答

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 
1
>>> s = '9999\\New_folder\\A\\23818\\files\\' 
>>> s.split('9999\\New_folder\\A\\')[1].split('\\')[0] 
'23818' 
0

解決方法有很多。 如果所有的路徑都像9999 \ New_folder \ A#number#\ files \那麼您可以簡單地通過查找第三個最後一個和最後一個「\」秒來獲取子字符串。 您可以使用rfind()(http://docs.python.org/library/string.html#string.rfind)

另一種更常用的方法是使用正則表達式。 http://docs.python.org/library/re.html

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]