0

我有一个.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

4 回答 4

1
>>> s = '9999\\New_folder\\A\\23818\\files\\'
>>> s.split('9999\\New_folder\\A\\')[1].split('\\')[0]
'23818'
于 2012-08-13T21:08:36.630 回答
0

有很多解决方案。如果所有路径都像 9999\New_folder\A#number#\files\ 那么您可以通过查找倒数第三个和倒数第二个“\”来简单地获取子字符串。您可以通过使用rfind()(http://docs.python.org/library/string.html#string.rfind)来做到这一点

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

于 2012-08-13T21:10:41.073 回答
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
于 2012-08-13T21:10:54.007 回答
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]
于 2012-08-13T21:23:38.853 回答