Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. ['/abs/path/foo',
  2. 'rel/path',
  3. 'just-a-file']
  4.  
  5. ['abs', 'rel', 'just-a-file']
  6.  
  7. In [69]: import os
  8.  
  9. In [70]: paths
  10. Out[70]: ['/abs/path/foo', 'rel/path', 'just-a-file']
  11.  
  12. In [71]: [next(part for part in path.split(os.path.sep) if part) for path in paths]
  13. Out[71]: ['abs', 'rel', 'just-a-file']
  14.  
  15. import os.path
  16.  
  17. def paths(p) :
  18. head,tail = os.path.split(p)
  19. components = []
  20. while len(tail)>0:
  21. components.insert(0,tail)
  22. head,tail = os.path.split(head)
  23. return components
  24.  
  25. for p in ['/abs/path/foo','rel/path','just-a-file'] :
  26. print paths(p)[0]
  27.  
  28. import PurePath from pathlib
  29. import os
  30.  
  31. # Separates the paths into parts and prints to the console...
  32. def print_path_parts(path: str):
  33.  
  34. path = PurePath(path)
  35. parts = list(path.parts)
  36.  
  37. # From your description, looks like you don't want the root.
  38. # Pop it off.
  39. if parts[0] == os.sep:
  40. parts.pop(0)
  41.  
  42. print(parts)
  43.  
  44. # Array of path strings...
  45. paths = ['/abs/path/foo',
  46. 'rel/path',
  47. 'just-a-file']
  48.  
  49. # For each path, print parts to the console
  50. for path in paths:
  51. print_path_parts(path)
  52.  
  53. ['abs', 'path', 'foo']
  54. ['rel', 'path']
  55. ['just-a-file']
  56.  
  57. >>> import re
  58. >>> paths = ['/abs/path/foo',
  59. ... 'rel/path',
  60. ... 'just-a-file']
  61. >>>
  62. >>> [re.match(r'/?([^/]+)', p).groups()[0] for p in paths]
  63. ['abs', 'rel', 'just-a-file']
  64.  
  65. >>> paths = [r'abspathfoo',
  66. ... r'relpath',
  67. ... r'just-a-file',
  68. ... r'C:abspathfoo',
  69. ... r'C:relpath',
  70. ... r'C:just-a-file']
  71. >>>
  72. >>> [re.match(r'(?:[A-Za-z]:)?\?([^\]+)', p).groups()[0] for p in paths]
  73. ['abs', 'rel', 'just-a-file', 'abs', 'rel', 'just-a-file']
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement