0

I have list of file paths inside C:\ stored in a list called filepaths, now i have to strip off C:\ from all the filepaths while doing a for loop.

I'm not able to find a strip method while looping, as each element is coming as Type list. Please find my code below.

filepaths = ['C:\folder\file1.jpg','C:\file2.png','C:\file3.xls']
tobestriped = 'C:\'
for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)
Ashwin
  • 245
  • 2
  • 7
  • 22

1 Answers1

0

Well, to begin with, in tobestriped you'll get an error as \' will be escaped. You can use tobestriped = 'C:\\'.

From this SO answer:

A "raw string literal" is a slightly different syntax for a string literal, in which a backslash, \, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on. In normal string literals, each backslash must be doubled up to avoid being taken as the start of an escape sequence.

Next, In your paths list \f will also be escaped. To get rid of this issue, make those strings raw strings:

filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']

An you will have the desired result:

filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']
tobestriped = 'C:\\'

for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)

Output:

folder\file1.jpg
file2.png
file3.xls

An alternative to your solution would be to take advantage of the fact that all your strings begin with C:\ so you can do something like this:

print([x[3:] for x in filepaths])
  • i'm not able to do `newfilepath = filepath.strip(tobestriped)` as you have mentioned in your answer. i'm getting this error, `AttributeError: 'list' object has no attribute 'strip'` – Ashwin Jul 04 '17 at 14:13
  • With the data you supplied, each of my solutions work. If your paths come themselves as lists, just to this before the for loop: `flat_list = [item for sublist in l for item in sublist]` –  Jul 04 '17 at 14:16
  • Does it make any difference in the approach if i'm reading a csv file and making my `filepaths` list ? – Ashwin Jul 04 '17 at 14:23
  • Let's not make this a never-ending story. Post all your relevant code and how your data actually looks like –  Jul 04 '17 at 14:33