首页 > 解决方案 > 如何使用 pandas 读取本地包模块中的 csv?

问题描述

我创建了一个 python 模块,其中包含许多用于我工作的各种任务的自定义函数。在模块内部,我希望能够读取本地 CSV 文件。

import pandas as pd

def my_function():
    print('Hello World')
    df = pd.read_csv('spreadsheet.csv') #This file is in the same folder as the module.
    return df

我在 jupyter notebook 中导入我的模块以尝试这样使用它:

import sys
sys.path.append('C:/Users/me/Documents/mymodule')
import mymodule

my_module.my_function()

但我会收到错误FileNotFoundError: [Errno 2] No such file or directory: 'spreadsheet.csv',因为它试图从我的 jupyter noteobok 文件夹而不是模块文件夹中读取它。

标签: pythonpandasmodule

解决方案


PATH用于查找与工作目录不同的命令。最好采用传文件给你打开的功能。同样出于测试目的,您会看到我使用了if __name__ == '__main__':模式

我的模块

import pandas as pd

def my_function(path):
    return pd.read_csv(path)

if __name__ == '__main__':
    from pathlib import Path
    print(my_function(Path().home().joinpath("PyCharmProjects/sensorvenv/jupyter/a.csv")))

朱庇特

from pathlib import Path
import mymodule
mymodule.my_function(Path().cwd().joinpath("a.csv"))

推荐阅读