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

问题描述

我已经在 Jupyter Notebook 中编写了一些代码,这些代码在Windows PC上本地运行。导入文件夹时,我使用“ \”

但是,我刚刚将所有文件夹移至了我的 google驱动器,并使用 Colab 将其打开了。 现在,目录路径中的文件夹用“ /” 分隔,从而出现错误

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

# 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. 


OUT:


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不允许我在本地查看它。

我的最终目标是:

  • 完全在线的仪表板(面板或其他)
  • 仪表板运行在服务器而非我的PC上(例如Heroku)
  • 我可以将链接发送给某人,他们可以查看。

也许有人可以解决这个问题,从而避免出现主要问题。

解决方法

人们可以使用pathlib模块来代替os模块,该模块可以从Python 3.4中获得。

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

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/..\\')

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


重写问题中的代码以使用pathlib:

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")))