Python, string slicing (getting file names from a list of file locations) -


I am trying to get the file name from the list of file locations I

  L = ['C: \\ Design \ dw \ file4.doc', 'C: It is that the string involves skiing.  

\\ light \ pdf \ download \ list.doc ',' c: \\ design \ dq \ file4g.doc ',' c: \\ design \ dq \ file4r.doc ',' c : \\ Design \ Dq \ File4k.doc ',' C: \\ Design \ Dq \ ole.doc ',' C: \\ GE \ easy \ file \ os_references (9) .doc ',' C: \\ For friend \ KLO \ Market \ BIZ \ C L: B = a.split ('\') for B in \: \ cPrint ('.doc'): c.replace ('.doc', '') LL.append (c) print LL

Question 1: Output is still '.doc'

Question 2: What's the better way to get a file name?

Thank you.

The first question is that the wire is irreversible, .replace () does not modify the string in place , That is:

  blaize @ bolt ~ $ python> & Gt; & Gt; S = "foobar"> gt; & Gt; & Gt; S2 = s.replace ("o", "x")> gt; & Gt; & Gt; Print S. Fobar & gt; & Gt; & Gt; Printed s2 fxxbar  

My answer to the second question is as follows:

  # I use ntpath because I'm running Linux on i # this The way is stronger than if you know that you will deal with the Windows path. # One option is to import from os.path, the Linux file name will work in Linux and the Windows path will work in Windows. From Ntpath import basename, use splitext # r to "justify people as a string #" \ N "Do not do that you think it might be. # See here: https: //docs.python .org / 2.0 / ref / strings.html Docs = [R'C: \ Design \ dw \ file4.doc ', r'C: \ light \ PDF \ Download \ list.doc', r'C: \ Design \ Dq \ file4g.doc ', r'C: \ Design \ DAC \ file4r.doc', r'C: \ Design \ Dq \ file4k.doc ', r'C: \ Design \ Dq \ ole.doc', r 'C: \ Design / Dq / test1 Doctor', # one corner case 'R' \\ some_unc_machine \ Design / Dq / test2.doc ', # Examine a corner case RC: \ ge \ easy \ file \ os_references (9) .doc ', r'C: \ Mate \ KLO \ Market \ BIZ \ KP \ jo \ Documents \ REF.doc'] # Please use meaningful variable names: basenames = [] For doc_path in docs: # Do not redo # Use the Bistin Path handling functions # There are many exceptions in file naming and # (especially on Windows) file_name = basename (doc_path) file_basename, extension = splitext (file_name) if extension == ". Doc ": basenames.append (file_basename) Print bossname  

Best luck friend Python is an excellent language.


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