簡體   English   中英

為什么Python open()函數不接受“目錄/文件名”作為參數?

[英]Why is Python open() function not accepting “directory/filename” as an argument?

本地環境:Python 3,Bottle,MacOs

遠程環境:Python 3,Bottle,Pythonanywhere

這在我的本地環境中有效,但在我的遠程環境中無效:

@route('/test')
def test():
    '''Function tests file open issue.'''
    with open('uploads/Project2.csv', 'r', newline='') as file:
        content = ""
        content = file.read()
    return content

這在我的遠程環境中有效,但在我的本地環境中無效:

@route('/test')
def test():
    '''Function tests file open issue.'''
    with open('uploads', 'r', newline='') as file:
        content = ""
        content = file.read()
    return content

在第一種情況下,我將文件路徑傳遞給open函數。 如果我將文件夾名稱傳遞給它,則會返回此錯誤:

IsADirectoryError:[Errno 21]是目錄:'uploads'

在第二種情況下,我將文件夾名稱傳遞給open函數。 如果我傳遞文件路徑,它將返回錯誤:

NotADirectoryError:[Errno 20]不是目錄:'uploads / Project2.csv'

我感到困惑。 有任何想法嗎?

首先,您必須確定該路徑在遠程服務器上是否存在。

import os 
os.path.exists(<your path>)

其次,您不必聲明您的內容變量,您可以像這樣聲明它。

content = file.read()

第三,

"uploads" is a directory not a file. Provide a file name in your
directory like you have provided in your local environment. if 
"upload" is not a subdirectory of your code directory, then provide
absolute path. like 
upload = "/home/ubuntu/env/uploads/projects.csv"

在這兩種環境中,“上載”是代碼目錄的子目錄,但是...

在本地環境中,相對路徑就足夠了:

"uploads/file"

在遠程環境中,需要絕對路徑:

"/home/my_projects/project/uploads/file"

我認為這與在遠程環境中而不是本地環境中將Bottle作為WSGI對象有關。

暫無
暫無

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

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