简体   繁体   English

Python pathlib.Path 库总是从路径中剪切最后一个文件夹并将其添加到创建文件的名称中

[英]Python pathlib.Path library always cuts last folder from the path and adds it to the name of created file

So here is the problem, I have some path which is like this:所以这是问题所在,我有一些路径是这样的:

get_path = 'C:/Users/user1/Desktop/Files/File/1/category/UFF/'

Then I use this to "make" it win path:然后我用它来“使”它赢得路径:

path = pathlib.Path(get_path)

So now every time I use it, to create some other files inside of path directory, my files are created inside of "category" folder with prefix UFF, so file names are:所以现在每次我使用它时,要在路径目录中创建一些其他文件,我的文件都是在带有前缀 UFF 的“类别”文件夹中创建的,所以文件名是:

category folder:

UFFNameFile1.xml
UFFNameFile2.xml

instead of代替

UFF folder:

NameFile1.xml
NameFile2.xml

For creation of files I use:为了创建我使用的文件:

tree.write(str(path)+name+'.xml', encoding='utf-8', xml_declaration=True)

Anyone has idea what is going on?有人知道发生了什么吗?

The last slash in get_path is dropped when passing to Path . get_path中的最后一个斜杠在传递给Path时被删除。 The string you are passing to tree.write is exactly what you are seeing: 'C:/Users/user1/Desktop/Files/File/1/category/UFFsomefilename.XML'您传递给tree.write的字符串正是您所看到的: 'C:/Users/user1/Desktop/Files/File/1/category/UFFsomefilename.XML'

You can fix this as followed:您可以按如下方式解决此问题:

path_out = path / f'{name}.xml'
tree.write(path_out.as_posix(), encoding='utf-8', xml_declaration=True)

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

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