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?

3
  • 5
    path[0:18] not path[0,18]. The : is your problem Commented Aug 1, 2018 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 Commented Aug 1, 2018 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. Commented Aug 1, 2018 at 13:45

3 Answers 3

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Or you can use the function os.path.dirname which is pretty much the same thing, but a little more explicit
Literally the same in fact but it is more explicit def dirname(p): """Returns the directory component of a pathname""" return split(p)[0]
0

You can replace with regex as well

import re
result = re.sub(r'\\[a-z]*.txt',  '',    path) 

Comments

-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.