The new Path package from the pathlib library, which has been added from Python 3.4, seems a powerful replacement of approaches such as os.path.join()
, but I've some trouble working with it.
I have a path that can be anything from folder_foo/file.csv
to long/path/to/folder_foo/file.csv
. I read the .csv file in folder_foo
with pandas, modify it and want to save it to folder_bar/file.csv
or long/path/to/folder_bar/file.csv
.
Essentially I want to rename folder_foo
to folder_bar
in the Path object.
EDIT: example path code
csv_path = Path("long/path/to/folder_foo/file.csv")
csv_path.parents[0] = csv_path.parents[0] + "_clean")
Which leads to the error TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'
, which means you cannot use +
to combine a PosixPath
with a str
as described in TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'.
To solve this I tried the following:
csv_path.parents[0] = Path(str(csv_path.parents[0]) + "_clean")
Which however results in the error : TypeError: '_PathParents' object does not support item assignment
.
Since PosixPath
is not a list, this error is understandable.
Maybe .parts
is a better approach, but
csv_path.parts[-2] = csv_path.parts[-2][:-3] + "bar"
results in: TypeError: 'tuple' object does not support item assignment
.
How can I easily rename the file's parent folder?
Python pathlib change directory We go inside another directory with os' chdir . #!/usr/bin/python from pathlib import Path from os import chdir path = Path('..') print(f'Current working directory: {path. cwd()}') chdir(path) print(f'Current working directory: {path. cwd()}') chdir('..')
pathlib. Path (WindowsPath, PosixPath, etc.) objects are not considered PathLike : PY-30747.
With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together. More powerful, with most necessary methods and properties available directly on the object.
Clicking on the Environment Variables button on the bottom right. In the System variables section, selecting the Path variable and clicking on Edit. The next screen will show all the directories that are currently a part of the PATH variable. Clicking on New and entering Python's install directory.
Would rather split this up for readability:
bar_folder = csv_path.parent.parent / 'folder_bar'
csv_path2 = bar_folder / csv_path.name
Having the destination folder as a variable also enables you to create the folder using for example:
bar_folder.mkdir(exist_ok=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With