简体   繁体   English

为什么Python open()函数不接受“目录/文件名”作为参数?

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

Local environment: Python 3, Bottle, MacOs 本地环境:Python 3,Bottle,MacOs

Remote environment: Python 3, Bottle, Pythonanywhere 远程环境:Python 3,Bottle,Pythonanywhere

This works in my local environment but not in my remote environment: 这在我的本地环境中有效,但在我的远程环境中无效:

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

This works in my remote environment but not in my local environment: 这在我的远程环境中有效,但在我的本地环境中无效:

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

In the first case, I pass a file path to the open function. 在第一种情况下,我将文件路径传递给open函数。 If I pass a folder name to it returns this error: 如果我将文件夹名称传递给它,则会返回此错误:

IsADirectoryError: [Errno 21] Is a directory: 'uploads' IsADirectoryError:[Errno 21]是目录:'uploads'

In the second case, I pass a folder name to the open function. 在第二种情况下,我将文件夹名称传递给open函数。 If I pass a file path it returns error: 如果我传递文件路径,它将返回错误:

NotADirectoryError: [Errno 20] Not a directory: 'uploads/Project2.csv' NotADirectoryError:[Errno 20]不是目录:'uploads / Project2.csv'

I am baffled. 我感到困惑。 Any ideas? 有任何想法吗?

First you have to be certain whether the path exists or not on your remote server. 首先,您必须确定该路径在远程服务器上是否存在。

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

second, you dont have to declare your content variable, you can just declare it like this. 其次,您不必声明您的内容变量,您可以像这样声明它。

content = file.read()

Third, 第三,

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

In both environments "uploads" is a subdirectory of the code directory but... 在这两种环境中,“上载”是代码目录的子目录,但是...

In the local environment a relative path was sufficient: 在本地环境中,相对路径就足够了:

"uploads/file"

In the remote environment an absolute path was required: 在远程环境中,需要绝对路径:

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

I think that this is to do with Bottle being a WSGI object in the remote environment but not in the local environment. 我认为这与在远程环境中而不是本地环境中将Bottle作为WSGI对象有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM