从带有混合斜杠的字符串中提取基本名称
Extracting basename from a a string with mixed slashes
我正在尝试从以下内容中提取基本名称 abcd.txt,这是我从对列表执行的连接操作中获得的:
path = "my/python/is/working"
list = ["abcd","efgh","ijkl"]
path_of_each_file = [path + "\" + x for x in list]
因此列表如下所示:
path[0] = ["my/python/is/working\abcd.txt","my/python/is/working\abcd.txt","my/python/is/working\abcd.txt"]
我正在使用以下方法从列表的每个元素中获取基本名称:
name_base = os.path.basename(path[0])
但我得到的输出是:
name_base = working\abcd.txt
我只需要 abcd.txt 作为我的基本名称。
提前致谢
如果我对你的问题的理解正确,下面的代码应该能帮到你:
path = "my/python/is/working"
list = ["abcd.txt","efgh.txt","ijkl.txt"]
path_of_each_file = [path + "\" + x for x in list]
for i in range(len(path_of_each_file)):
print(os.path.basename(path_of_each_file[i]))
输出:
abcd.txt
efgh.txt
ijkl.txt
现代方式:
from pathlib import Path
path = Path("my/python/is/working")
flist = ["abcd.txt","efgh.txt","ijkl.txt"]
path_of_each_file = [path / x for x in flist]
for p in path_of_each_file:
print(p.name)
- 使用 pathlib 模块实现可移植性。
list
是列表对象的类型名,不建议作为变量名使用。
- “/”是连接 Path 对象的运算符。
- 使用
for elem in alist: ...
更像 pythonic。
np.name
相当于使用路径库时的 os.path.basname(op)
。
我正在尝试从以下内容中提取基本名称 abcd.txt,这是我从对列表执行的连接操作中获得的:
path = "my/python/is/working"
list = ["abcd","efgh","ijkl"]
path_of_each_file = [path + "\" + x for x in list]
因此列表如下所示:
path[0] = ["my/python/is/working\abcd.txt","my/python/is/working\abcd.txt","my/python/is/working\abcd.txt"]
我正在使用以下方法从列表的每个元素中获取基本名称:
name_base = os.path.basename(path[0])
但我得到的输出是:
name_base = working\abcd.txt
我只需要 abcd.txt 作为我的基本名称。
提前致谢
如果我对你的问题的理解正确,下面的代码应该能帮到你:
path = "my/python/is/working"
list = ["abcd.txt","efgh.txt","ijkl.txt"]
path_of_each_file = [path + "\" + x for x in list]
for i in range(len(path_of_each_file)):
print(os.path.basename(path_of_each_file[i]))
输出:
abcd.txt
efgh.txt
ijkl.txt
现代方式:
from pathlib import Path
path = Path("my/python/is/working")
flist = ["abcd.txt","efgh.txt","ijkl.txt"]
path_of_each_file = [path / x for x in flist]
for p in path_of_each_file:
print(p.name)
- 使用 pathlib 模块实现可移植性。
list
是列表对象的类型名,不建议作为变量名使用。- “/”是连接 Path 对象的运算符。
- 使用
for elem in alist: ...
更像 pythonic。 np.name
相当于使用路径库时的os.path.basname(op)
。