python - 如何使用 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 文件夹而不是模块文件夹中读取它。
解决方案
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"))
推荐阅读
- perl - `print $fh <<'EOF'`中的here-doc问题:Perl执行here doc
- xaml - 如何在 UWP 中将 WebView 转换为 IRandomAccessStream?
- laravel - 客户端尝试使用旧密码连接到 redis
- python - Python - 如何在 django 模板中为所有值并排显示两个键的字典值
- python - 为什么梯度带张量流使张量的总和?
- c# - 尝试设置配置值`IHostBuilder`,但未反映在启动类中的 ConfigureServices - asp.net core 3.1
- sorting - 颤动按日期对数组列表进行排序
- javascript - “字符串”类型上不存在 Typescript 属性“标签”
- aws-lambda - 如何在 CodeBuild 中为 Lambda 函数添加 Python 库依赖项
- java - Spring Boot JPA 获取列表并向其中添加项目会引发错误