You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python与R中Feather包如何修改默认写入目录?

解决Jupyter Notebook中R/Python自定义Feather文件存储路径的问题

我来帮你搞定这个问题——你当前的代码只指定了文件名,没有给出完整的目标路径,所以系统默认把文件存在了你的用户目录C:\Users\murali(或者Jupyter启动时的工作目录)。要存到其他目录,只需要在路径参数里传入完整的文件夹路径+文件名就行,分R和Python两种情况给你具体方案:


R语言实现步骤

你只需要修改path变量为完整的目标路径,Windows系统里路径可以用正斜杠/或者双反斜杠\\(因为单反斜杠是转义字符):

library(feather)

# 示例:把文件存到D盘的Data/FeatherFiles目录下
# 方式1:用正斜杠(推荐,不用转义)
target_path <- "D:/Data/FeatherFiles/my_data.feather"
# 方式2:用双反斜杠
# target_path <- "D:\\Data\\FeatherFiles\\my_data.feather"

# 如果目标目录还不存在,先创建(recursive=TRUE允许创建嵌套文件夹)
dir.create("D:/Data/FeatherFiles", recursive = TRUE, showWarnings = FALSE)

# 写入Feather文件
write_feather(mtcars, target_path)
# 读取时也要用同样的完整路径
df <- read_feather(target_path)

小技巧

可以先运行getwd()查看R当前的工作目录,确认默认存储位置,方便排查问题。


Python语言实现步骤

最新版的feather推荐使用feather.write_dataframe方法,同样只需要传入完整的目标路径即可:

import feather
import pandas as pd
import numpy as np
import os

# 生成你的测试数据
arr = np.random.randn(10000)
arr[::10] = np.nan
df = pd.DataFrame({'col1': arr, 'col2': np.random.randint(0, 100, size=10000)})

# 指定完整目标路径
target_path = "D:/Data/FeatherFiles/python_data.feather"
# 或者用双反斜杠:target_path = "D:\\Data\\FeatherFiles\\python_data.feather"

# 先创建目标目录(exist_ok=True避免目录已存在时报错)
os.makedirs("D:/Data/FeatherFiles", exist_ok=True)

# 写入Feather文件
feather.write_dataframe(df, target_path)
# 读取文件
read_df = feather.read_dataframe(target_path)

小技巧

运行import os; print(os.getcwd())可以查看Python当前的工作目录,确认默认存储位置。


Jupyter Notebook的额外提示

如果不想每次都写长长的完整路径,可以把常用的目标目录存成变量,复用起来更方便:

  • R:
    base_dir <- "D:/Data/FeatherFiles"
    file_path <- file.path(base_dir, "my_data.feather")
    
  • Python:
    base_dir = "D:/Data/FeatherFiles"
    file_path = os.path.join(base_dir, "python_data.feather")
    

内容的提问来源于stack exchange,提问作者Murali

火山引擎 最新活动