Python:使用正斜杠和反斜杠导航目录

Python: Navigate directories using forwardslash and backslash

我在 Jupyter Notebook 中编写了一些代码,这些代码在我的 windows PC 上本地运行。当它导入文件夹时,我使用 "\".

但是我刚刚将所有文件夹移动到我的 google 驱动器, 并使用 Colab 打开它。 现在目录路径中的文件夹用 "/" 分隔,因此出现错误。

无论我是 运行 在我的 PC 上本地还是在线,如何导入 foders。

# added this bit so i can import and run the code in colab 
import os
from google.colab import drive
drive.mount('/content/drive')
os.chdir('/content/drive/My Drive/Dashboarding_Project/Folder_with_all_IV_curves/Python_IV')

#From the JUPYTER NOTEBOOK file 

import pandas as pd
import os
import re


 #these variables contain hte excell file with hte mask info & the file with the batch info 
meta_mask_name = "MASK-1_2020-03-01.xlsx"
meta_batch_name = "BATCH-1-2_2020-8-20--EXAMPLE.xlsx"


 #This is the main directory of the foler structure 
path_parent = os.path.dirname(os.getcwd())

print("Main folder: ", path_parent)
print("Folders: ",  os.listdir(path_parent))
print (os.listdir(path_parent +r"\MASK_META")) # this gives error now that i am using it online. 


输出:


FileNotFoundError: [Errno 2] No such file or directory: '/content/drive/My Drive/Dashboarding_Project/Folder_with_all_IV_curves\MASK_META'

上下文

我同时使用 Colab 和 Jupiter,因为:

  • Colab 易于共享,无需下载任何内容,可在任何地方访问。
  • 我可以在本地使用和部署 Jupyter PANEL,而 Colab 不允许我在本地查看它。

我的结局objective是:

  • 完全在线的仪表板(面板或其他东西)
  • Dashboard 在服务器上运行,而不是我的 PC(如 Heroku)
  • 我可以将 link 发送给某人,他们可以查看。

也许有人有解决这个问题的方法,可以避免主要问题。

可以使用 pathlib 模块代替 os 模块,可从 Python 3.4.

获得

pathlib 模块为文件系统操作提供了 API。 pathlib.Path class 是所有支持平台的文件系统路径的可移植表示:

from pathlib import Path

# Print the user's home directory
print(Path.home())
# Windows example output:
# WindowsPath('C:/Users/username')
# Linux example output:
# PosixPath('/home/username')

pathlib.Path 适用于所有平台上的正斜杠路径分隔符。下面是一个 Windows 示例:

Path.home().joinpath('../').resolve()
# WindowsPath('C:/Users')

然而,反斜杠不会像预期的那样在所有平台上工作:

Path.home().joinpath('..\').resolve()  # Note double backslash is required for backslash escaping
# On Windows:
# WindowsPath('C:/Users')
# On Linux:
# PosixPath('/home/username/..\')

我的建议是在所有平台上使用 Posix-like 路径(正斜杠分隔符),pathlib.Path 提供路径分隔符的映射。


重写问题中的代码以使用路径库:

from pathlib import Path


path_parent = Path.cwd().parent


def dir_contents_as_string(directory):
    # Explicit conversion of Path to str is required by str.join()
    return ", ".join(str(path) for path in directory.iterdir())


print("Main folder: ", str(path_parent))
print("Main folder contents: ",  dir_contents_as_string(path_parent))
print(dir_contents_as_string(path_parent.joinpath("MASK_META")))