python - Split a string by backslash -


I am trying to divide a path to get the name of the file, in the last part of the string, and I I am working with a problem I can not solve with:

My string: to = 'c: \ user \ desktop \ test \ excel_ports \ 1837.xlsx'

I did this:

  & gt; & Gt; & Gt; Te.split ('\\') ['C:', 'User', 'Desktop', 'Test', 'Excel_Reports xx837.xlsx'] & gt; & Gt; & Gt; Te.split ('\\') [-] 'Excel_Reports \ x01837.xlsx'  

I do not know what is the problem with \ 0 or \ number .... Is this a special Python character?

Here's what I want:

  ['c:', 'user', 'desktop', 'exam', 'excel_ports', '1837.xlsx' ]  

But I can not do this at all.

PD: There is no valid solution such as file_name = te [-5: -1] because the name of the excel file can be different at any time, although the usual number. Edit None, how to find "Load Excel") in the Oslistdir (folder): if f.endswith (".xlsx"): te = os.path.join (str (folder), str (f) )) #bla, bla, bla, ...... Thanks for all the replies and comments, they told me in the right direction. However, I resolved this issue by Rebecca NG this line:

  Code> te = os.path.join (str (folder), str (f))  

For this one:

  te = os Path.join (folder, f)  

And then, it works:

  te.split ('\\') [- 1] .split ('.') [0]  

returns the file name (number) without extension xlsx

You need to make text te for a raw string

Rw> & gt; & Gt; & Gt; Te = r'C: \ Users \ Desktop \ test \ Excel_Reports \ 1837.xlsx '& gt; & Gt; & Gt; Import OS & gt; & Gt; & Gt; Te.split ("\\") # OS can not use path.sep because my rip is on linux ['c:', 'user', 'desktop', 'test', 'excel_ports',' 1837 Xlsx ']

This dragon is due to syntax for literal strings \ g , \ n , \ t < / Code> etc. will also create problems. Do not need to avoid other slashes, because this character is not a valid escape sequence - but it is confused as hell. Better to use raw string syntax

If you are getting te from a source file other than an example, for example an ini file or database (as you would like ), You can not even see this problem


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -