如何在python中将文件路径和文件名拆分为组件?

时间:2014-08-04 20:48:15

标签: python

我想拆分" C:\ My Work \ Tester Related \ A_B_C.txt" 在Python中使用[C:\,My Work,Tester Related,A,B,C,txt]。

我刚开始学习Python。我确实导入了os.path模块,然后玩了 交互式提示中的某些功能但无法获得所需的结果。 谢谢您的帮助。我能够使用os.path.basename来获取文件,但是无法根据给定的分隔符' _'将文件拆分为组件。

3 个答案:

答案 0 :(得分:2)

s = "C:\\My Work\\Tester Related\\A_B_C.txt"

import re
print (re.split(r"\\|\.|\_",s))
['C:', 'My Work', 'Tester Related', 'A', 'B', 'C', 'txt']

答案 1 :(得分:0)

original_path = "C:\My Work\Tester Related\A_B_C.txt"

# Must quote the backslash in this case.
split_path = original_path.split("\\")

# At this point, split_path looks like:
# ['C:', 'My Work', 'Tester Related', 'A_B_C.txt']

split_filename = split_path[-1].split("_")
# split_filename is ['A', 'B', 'C.txt']

split_ext = split_filename[:-1].split(".")
# split_ext is ['C', 'txt']

split_filename = split_filename[:-1] + split_ext
# split_filename is ['A', 'B', 'C', 'txt']

split_path = split_path[:-1] + split_filename
# ['C:', 'My Work', 'Tester Related', 'A', 'B', 'C', 'txt']

它有点hacky但它​​会起作用。

答案 2 :(得分:0)

一个丑陋的两个班轮!

import itertools
txt = r"C:\\My Work\\Tester Related\\A_B_C.txt"

result = list(itertools.chain(*map(lambda x: x.split('_'), txt.split(os.path.sep))))
result = result[:-1] + list(os.path.splitext(result[-1]))

更好的方法是使用re,正如@PaedricCunningham在答案中所做的那样。

re.split(r"\\|\.|_", txt)