0

In column df['2'] I have a path with a filename:

C:\file1.txt

With code below I wanted to split off the filename:

df['2'].str.split('', n = 2, expand = True)

I get this error:

 File "<ipython-input-136-fe70d6bdb12c>", line 1
    df['2'].str.split('\', n = 2, expand = True)
                                                           ^
SyntaxError: EOL while scanning string literal

What am I doing wrong? It works for every other string I put in there.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

0

you are escaping the ' char with \ so the string literal is invalid and the interpreter finds a Syntax Error

I would recommend to use os.path for this kind of operations on path names, it is easy and and as a bonus it will work on every OS.

MarcoP
  • 1,438
  • 10
  • 17
0

instead of df['2'].str.split('\', n = 2, expand = True) try df['2'].str.split(chr(92), n = 2, expand = True)

poisonbox
  • 16
  • 2
0

If you're using python 3.4 or newer, the built in pathlib library works really well with paths. It eliminates most of the pain from / and . To get your implementation to work Krishnas suggestion in the comments should do the trick.

Here is anyway how to do this with pathlib:

from pathlib import Path

filename = Path(df['2'].str).stem

https://docs.python.org/3/library/pathlib.html