如何在 jupyter notebook 中指定文件路径

在 jupyter notebook/google colab 中指定文件路径时遇到问题。这是我找到的示例代码:


import csv


csvFile = 'myData.csv'

xmlFile = 'myData.xml'


csvData = csv.reader(open(csvFile))

xmlData = open(xmlFile, 'w')

我不知道上面代码的作者将 myData.csv 放在哪里,所以我尝试了这段代码来定位我的文件:


csvFile = 'C:\Users\...\myData.csv'

但我收到此错误:


SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape


我也试过这段代码:


csvFile = r'C:\Users\...\myData.csv'

但我收到此错误: FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\...\myData.csv'


我的问题是: 1. 上面代码的作者将 myData.csv 放在哪里?2.如何指定文件位置?


尚方宝剑之说
浏览 310回答 3
3回答

慕姐4208626

我尝试使用正斜杠和双反斜杠。两者都有效。'C:\\Users\\SAVK\\Downloads\\Ex_Files_Intro_Data_Science\\Ex_Files_Intro_Data_Science\\Exercise Files\\state_baby_names.csv''C:/Users/SAVK/Downloads/Ex_Files_Intro_Data_Science/Ex_Files_Intro_Data_Science/Exercise Files/us_baby_names.csv'例子 :states_babies = pd.read_csv('C:\\Users\\SAVK\\Downloads\\Ex_Files_Intro_Data_Science\\Ex_Files_Intro_Data_Science\\Exercise Files\\state_baby_names.csv');states_babies = pd.read_csv('C:/Users/SAVK/Downloads/Ex_Files_Intro_Data_Science/Ex_Files_Intro_Data_Science/Exercise Files/us_baby_names.csv');

茅侃侃

如果作者直接调用该文件,则它位于运行 Jupyter Notebook 的同一文件夹中以下之一应该可以从不同位置调用文件:一个。用双引号替换单引号并转义斜杠 ex。csvFile = "C:\\Users\\...\\myData.csv"湾。用双引号替换单引号并使用正斜杠 ex。csvFile = "C:/Users/.../myData.csv"

一只名叫tom的猫

我通过将 Google Colab 安装到 Google Drive 解决了这个问题。这是我挂载到 Google Drive 后的路径:csvFile = '/content/drive/My Drive/Colab Notebooks/myData.csv.txt'xmlFile = '/content/drive/My Drive/Colab Notebooks/myData.xml'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python