简体   繁体   English

Python:如何将 go 一个文件夹返回到 pathlib

[英]Python: How to go one folder back in pathlib

After watching my work folder get cluttered I have moved code files corresponding together into a subfolder.在看到我的工作文件夹变得混乱之后,我将相应的代码文件一起移动到了一个子文件夹中。 The problem is that the data my program uses is itself placed in a subfolder of the now parent folder.问题是我的程序使用的数据本身放在现在父文件夹的子文件夹中。 I used pathlib to extract the data from the subdirectories like so:我使用pathlib从子目录中提取数据,如下所示:

DATA_DIR = pathlib.Path.cwd().joinpath("Kokam NMC 46 Ah EET","CheckUps",
                                       "Calend_ID{id_nr}_{temp}_{SoC}".format(id_nr = id_nr, temp = temp, SoC = SoC ))

where Kokam NMC 46 Ah EET is the parent folder to CheckUps and so on.其中Kokam NMC 46 Ah EETCheckUps等的父文件夹。 Now what I need is to adjust this command in such a way that the path goes back into the parent folder and then into Kokam NMC 46 Ah EET etc. I had done some research on this site and tried what seemed like a solution in some cases, namely to add ".."现在我需要调整这个命令,使路径回到父文件夹,然后进入Kokam NMC 46 Ah EET等。我在这个网站上做了一些研究,并在某些情况下尝试了看起来像解决方案的方法,即加".."

DATA_DIR = pathlib.Path.cwd().joinpath("..","Kokam NMC 46 Ah EET","CheckUps",
                                       "Calend_ID{id_nr}_{temp}_{SoC}".format(id_nr = id_nr, temp = temp, SoC = SoC ))

which did not work.这没有用。 Similarly I tried the same strategy for saving a plot同样,我尝试了相同的策略来保存 plot

plt.savefig('../Graphs/Impedanz Plot von ID{id_nr} NMC{nmc_nr} bei {x} Hertz'.format(id_nr = id_nr, temp = temp, SoC = SoC, nmc_nr = nmc_nr, x=hertz),
                bbox_inches = 'tight', dpi = 600)

which returned返回

FileNotFoundError: [Errno 2] No such file or directory: '../Graphs/Impedanz von ID01 NMC46 (bei 35C und 100SOC).png'

How does one adjust for backtracking into parent folders using pathlib ?如何使用pathlib调整回溯到父文件夹? And if pathlib does not have this feature is there another way to do it?如果pathlib没有此功能,还有其他方法吗?

Thank you!谢谢!

Instead of .. , do path.parent :而不是.. ,做path.parent

>>> pathlib.Path.cwd()
PosixPath('/home/jan/Downloads')
>>> pathlib.Path.cwd().parent
PosixPath('/home/jan')

For your second attempt, make Python calculate an absolute path from a relative one.对于第二次尝试,让 Python 从相对路径计算绝对路径。

>>> os.path.abspath('../')
'/home/jan'

Also make sure the path you are trying to save to is the actually correct path by printing it.还要通过打印确保您尝试保存的路径是实际正确的路径。

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

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