簡體   English   中英

無法訪問主目錄中的文件(Jupyter Notebook)

[英]Unable to access file in home directory (Jupyter Notebook)

我正在嘗試在此處創建一個簡單的Jupyter Notebook。 在我的代碼中,我必須加載文件file.txt ,該文件位於home的/data目錄中

data/file.txt

open('data/file.txt', 'r')

要么

open('~/data/file.txt', 'r')

我收到一個錯誤

FileNotFoundError:[錯誤2]沒有這樣的文件或目錄:'〜/ data / file.txt'

您可以使用os.path.expanduser函數訪問主目錄以獲取主目錄的名稱。

import os
import os.path

# Create data directory
try:
    os.makedirs(os.path.join(os.path.expanduser('~'), 'data'))
except OSError:
    pass

# Write to file
with open(os.path.join(os.path.expanduser('~'), 'data/file.txt'), 'w') as f:
    f.write('Hello world')

# Read from file    
with open(os.path.join(os.path.expanduser('~'), 'data/file.txt')) as f:
    print(f.read())

Hello world

默認情況下,Jupyter筆記本始終在筆記本啟動的目錄上運行,因此您應該通過文件的相對路徑( ./ )引用該文件。

例如。 這有效:

with open('./data/file.txt') as f:
    for line in f.readlines():
        print(line.strip())

因此,使用./<any_dirpath>/<file>可以在本地jupyter安裝中使用。

如果您使用活頁夾或任何遠程站點,則主目錄不是您的本地目錄,而是遠程目錄,因此,除非您上載正在使用的文件,否則將無法讀取它。

您可以通過運行以下命令檢查當前目錄:

import os
print(os.getcwd() + "\n")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM