18
votes

I have files that I want only 'foo' and 'bar' left from split.

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

files

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

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

I thought since dn and .txt are pre-defined I could subtract, nope. Split does not work for me.

5

5 Answers

60
votes

How about using the proper 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')
4
votes

To deal with path and file names, it is best to use the built-in module os.path in Python. Please look at function dirname, basename and split in that module.

2
votes

simple Example for your Help.

import os
from os import path

path_to_directory = "C:\\X\\Data"

for f in os.listdir(path_to_directory):
    name , extension = path.splitext(f)
    print(name)

Output

foo
bar
0
votes

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\\")]

It seems you've left out some code. From what I can tell you're trying to split the contents of the file.

To fix your problem, you need to operate on a list of the files in the directory. That is what os.listdir does for you. I've also added a more sophisticated split. rsplit operates from the right, and will only split the first . it finds. Notice the 1 as the second argument.

0
votes

another example:

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