使用Reticulate调用文件功能

时间:2017-06-29 17:45:23

标签: python r reticulate

我想使用reticulate在R:

中重现此Python代码
file("my.png").read()

在R中我试过这个:

library(reticulate)
funcs <- import_builtins()
funcs$file("my.png").read()

这个错误说funcs$file不是函数。

我不清楚如何将文件路径传递给Python file函数。

非常感谢任何指导。

1 个答案:

答案 0 :(得分:1)

这是一个非常简单的(&#34; raw&#34;)示例,用于使用reticulate和Python内置函数读取文件。
myfile.txt的内容是:

ds y
"2017-05-23 08:07:00" 21.16641
"2017-05-23 08:07:10" 16.79345
"2017-05-23 08:07:20" 16.40846
"2017-05-23 08:07:30" 16.24653
"2017-05-23 08:07:40" 16.14694
"2017-05-23 08:07:50" 15.89552

并且读取文件的代码是:

library(reticulate)
funcs <- import_builtins()

fl <- funcs$open("myfile.txt", "r")
txt <- fl$readlines()    
fl$close()

cat(txt)

#  ds y
#  "2017-05-23 08:07:00" 21.16641
#  "2017-05-23 08:07:10" 16.79345
#  "2017-05-23 08:07:20" 16.40846
#  "2017-05-23 08:07:30" 16.24653
#  "2017-05-23 08:07:40" 16.14694
#  "2017-05-23 08:07:50" 15.89552

使用内置file功能的替代解决方案是:

fl <- funcs$open("myfile.txt", "r")
txt <- funcs$file$readlines(fl)  
fl$close()