Skip to content
Advertisement

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:

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?

Advertisement

Answer

The last slash in get_path is dropped when passing to 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'

You can fix this as followed:

path_out = path / f'{name}.xml'
tree.write(path_out.as_posix(), encoding='utf-8', xml_declaration=True)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement