0

I tried imitating my code in simple steps on python prompt:

>>> path="D:/workspace/a/b\\c\\d.txt"
>>> path[0,18]

But it gives me following error:

TypeError: string indices must be integers

I wanted to retrieve only directory as path. That is, I want to strip away the file name: D:/workspace/a/b\\c

Why I am getting this error?

MsA
  • 2,599
  • 3
  • 22
  • 47
  • 5
    `path[0:18]` not `path[0,18]`. The `:` is your problem – W Stokvis Aug 01 '18 at 13:34
  • `path[0,18]` is parsed by Python as "look up index `(0, 18)` in the path", and you can't index a string by a tuple – Edward Minnix Aug 01 '18 at 13:42
  • The index styling you used works for 2d arrays. If `arr = np.array([[1,2,3,4,5],[6,7,8,9,1]])` then `print (arr[0,4])` will result in `4`. This is just to show that `[0,4]` is not wrong and works on 2d arrays but not on the string you provided. – Sheldore Aug 01 '18 at 13:45

3 Answers3

2

path[0,18] should be path[0:18] or path[:18]

Even better (will work not matter what length the parent directory is):

import os
os.path.split(path)[0]
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
  • 1
    Or you can use the function `os.path.dirname` which is pretty much the same thing, but a little more explicit – Edward Minnix Aug 01 '18 at 13:41
  • Literally the same in fact but it is more explicit `def dirname(p): """Returns the directory component of a pathname""" return split(p)[0]` – FHTMitchell Aug 01 '18 at 13:46
0

You can replace with regex as well

import re
result = re.sub(r'\\[a-z]*.txt',  '',    path) 
mad_
  • 8,121
  • 2
  • 25
  • 40
-1
path="some/again_a_dir/file.txt"
print(path[0:16])

When we want to get a range of letters from the string, we should use ":" to define the range. path[0:16] means get items from the 1st element to 17th element of your string.

Vignesh SP
  • 451
  • 6
  • 15