30

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.

Merlin
  • 24,552
  • 41
  • 131
  • 206

6 Answers6

84

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')
Community
  • 1
  • 1
Martlark
  • 14,208
  • 13
  • 83
  • 99
4

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.

Nam Nguyen
  • 1,765
  • 9
  • 13
3

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
Deepak Raj
  • 462
  • 5
  • 15
2

Using python3 and pathlib:

import pathlib
f = 'C:\\X\\Data\\foo.txt'
print(pathlib.PureWindowsPath(f).stem)

will print: 'foo'

Thomas Vincent
  • 158
  • 1
  • 6
1

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.

Tim McNamara
  • 18,019
  • 4
  • 52
  • 83
1

another example:

f.split('\\')[-1].split('.')[0]
Arash
  • 383
  • 4
  • 16