I have a list of paths that looks like this C:/Users/myuser/Documents/files\my_file_1.csv
and I want to get the file name from that by doing this:
path=['C:/Users/myuser/Documents/files\my_file_1.csv','C:/Users/myuser/Documents/files\my_file_2.csv',...]
filename, file_extension = os.path.splitext(path[0])
and I always get 'C:/Users/myuser/Documents/files\my_file_1'
I know it must be for the ' \ ' slash but I haven't been able to replace it. Can anyone give me an idea?
You can use os.path.basename
to get just the filename without the full directory, then os.path.splitext
to remove the file extension.
>>> import os
>>> [os.path.splitext(os.path.basename(i))[0] for i in path]
['my_file_1', 'my_file_2']
Or if you want the filename and extension, but no directories
>>> [os.path.basename(i) for i in path]
['my_file_1.csv', 'my_file_2.csv']
As you are using windows and if you are using python 3.4+
>>> from pathlib import PureWindowsPath
>>> path=['C:/Users/myuser/Documents/files\my_file_1.csv','C:/Users/myuser/Documents/files\my_file_2.csv']
>>> print([PureWindowsPath(i).name for i in path])
['my_file_1.csv', 'my_file_2.csv']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.