Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split filenames with python

Tags:

python

file

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.

like image 808
Merlin Avatar asked Sep 05 '11 05:09

Merlin


3 Answers

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')
like image 117
Martlark Avatar answered Sep 27 '22 15:09

Martlark


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.

like image 21
Nam Nguyen Avatar answered Sep 27 '22 17:09

Nam Nguyen


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
like image 38
CodePerfectPlus Avatar answered Sep 27 '22 15:09

CodePerfectPlus