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.
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')
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.
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)
foo
bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With