Separate file names with python

I have files that I only need for "foo" and "bar" to the left of split.

dn = "C:\\X\\Data\\" 

files

 f= C:\\X\\Data\\foo.txt f= C:\\X\\Dats\\bar.txt 

I tried f.split(".",1)[0]

I thought that since dn and .txt are predefined, I could subtract, no. Split does not work for me.

+8
python file
source share
4 answers

How to use the correct path handling methods from os.path?

 >>> f = 'C:\\X\\Data\\foo.txt' >>> import os >>> os.path.basename(f) 'foo.txt' >>> os.path.dirname(f) 'C:\\X\\Data' >>> os.path.splitext(f) ('C:\\X\\Data\\foo', '.txt') >>> os.path.splitext(os.path.basename(f)) ('foo', '.txt') 
+26
source share

To deal with path and file names, it is best to use the os.path built-in module in Python. See the dirname , basename and split functions in this module.

+2
source share

These two lines return a list of file names without extensions:

 import os [fname.rsplit('.', 1)[0] for fname in os.listdir("C:\\X\\Data\\")] 

You seem to have left the code. From what I can tell, you are trying to split the contents of a file.

To fix your problem, you need to operate with a list of files in the directory. This is what os.listdir does for you. I also added a more complex split. rsplit works on the right, and only breaks the first one found . . Note 1 as the second argument.

+1
source share

another example:

 f.split('\\')[-1].split('.')[0] 
-one
source share

All Articles