我想在给定文件路径的中间插入一个目录名,如下所示:
directory_name = 'new_dir'
file_path0 = 'dir1/dir2/dir3/dir4/file.txt'
file_path1 = some_func(file_path0, directory_name, position=2)
print(file_path1)
>>> 'dir1/dir2/new_dir/dir3/dir4/file.txt'
Run Code Online (Sandbox Code Playgroud)
我查看了 os.path 和 pathlib 包,但看起来它们没有允许在文件路径中间插入的功能。我试过:
import sys,os
from os.path import join
path_ = file_path0.split(os.sep)
path_.insert(2, 'new_dir')
print(join(path_))
Run Code Online (Sandbox Code Playgroud)
但这会导致错误
“需要 str、bytes 或 os.PathLike 对象,而不是列表”
有谁知道允许在文件路径中间插入这样的标准Python函数?或者 - 我怎样才能转向path_可以处理的东西os.path。我是 pathlib 的新手,所以也许我错过了一些东西
编辑:根据问题的答案,我可以建议以下解决方案:
1.)正如 Zach Favakeh 所建议的和这个答案join(*path_)中所写的那样,只需使用“splat”运算符将上面的代码更正即可*,一切都解决了。
2.)按照buran的建议,您可以使用该pathlib软件包,简而言之,它会导致:
from pathlib import PurePath
path_list = list(PurePath(file_path0).parts)
path_list.insert(2, 'new_dir')
file_path1 = PurePath('').joinpath(*path_list)
print(file_path1)
>>> 'dir1/dir2/new_dir/dir3/dir4/file.txt'
Run Code Online (Sandbox Code Playgroud) 我正在尝试df['column_name'].str.count("+")在 python 熊猫中使用,但我收到
“错误:没有什么可重复的”
. 使用常规字符,该方法有效,例如df['column_name'].str.count("a")工作正常。
另外,“^”符号也有问题。如果我使用df['column_name'].str.contains("^")结果不正确 - 看起来“^”被解释为“”(空白)。
令人惊讶的是,如果我在常规的非熊猫字符串上使用.count("+")和.contains("^"),它们工作得非常好。
简单的工作示例:
df = pd.DataFrame({'column1': ['Nighthawks+', 'Dragoons'], 'column2': ['1st', '2nd']}, columns = ['column1', 'column2'])
Run Code Online (Sandbox Code Playgroud)
当应用df["column1"].str.contains("^")一个得到“真,真”但应该是“假,假”。
当应用df["column1"].str.count("+")一个得到
“错误:没有什么可重复的”
但是,在熊猫之外,"bla++".count("+")正确地给出结果“2”。
任何解决方案?谢谢