简体   繁体   English

从导入模块的目录中读取文件

[英]Reading a file from the directory which module is imported

I am trying to read a file in a custom module I have created in Python.我正在尝试读取在 Python 中创建的自定义模块中的文件。 But it is showing error when I try to do so.但是当我尝试这样做时它显示错误。

Directory structure目录结构

base/
|
|_ app.py
|_ cmod/
   |
   |_ __init__.py
   |_ util.py
   |_ db.csv

util.py snippet util.py片段

from csvhandler import CSVFile

def get_db():
    with open("db.csv", "r+") as db:
        data = CSVFile(db)
    return data

app.py snippet app.py片段

from cmod import util
data = util.get_db()

It throws the following error它抛出以下错误

FileNotFoundError: [Errno 2] No such file or directory: 'db.csv'

Is there any issue with imports of placement?放置的导入有什么问题吗?
Note: The db.csv has to be put there only.注意: db.csv只能放在那里。

The current working directory when you run this is likely the one app.py sits in. open() looks for files in the current working directory, not the directory of the currently executing file.运行它时的当前工作目录可能是 app.py 所在的一个。 open() 在当前工作目录中查找文件,而不是当前执行文件的目录。

The most portable way to open a file stored relatively would be to get the full path to the python file, isolate the directory, and then join it.打开相对存储的文件最便携的方法是获取 python 文件的完整路径,隔离目录,然后加入它。

util.py

import os

def get_db():
    directory = os.path.dirname(__file__)
    with open(os.path.join(directory, "db.csv"), "r+") as db:
        data = CSVFile(db)
    return data

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

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