简体   繁体   English

Python 文件名来自带有 \ 的路径

[英]Python filename from path with \

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:我有一个看起来像C:/Users/myuser/Documents/files\my_file_1.csv的路径列表,我想通过这样做来获取文件名:

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.我总是得到'C:/Users/myuser/Documents/files\my_file_1'我知道它必须是'\'斜线,但我无法替换它。 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.您可以使用os.path.basename仅获取文件名而不获取完整目录,然后使用os.path.splitext删除文件扩展名。

>>> 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+当您使用 windows 并且如果您使用 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM