0

I want to use reticulate to reproduce this Python code in R:

file("my.png").read()

In R I have tried this:

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

This errors saying that funcs$file is not a function.

It isn't clear to me how I would pass a filepath to the Python file function.

Any guidance would be greatly appreciated.

Carl
  • 5,569
  • 6
  • 39
  • 74

1 Answers1

1

Here is a very simple (and "raw") example for reading a file using reticulate and the Python built-in functions.
The content of myfile.txt is:

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

and the code to read the file is:

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

An alternative solution using the built-in file function is:

fl <- funcs$open("myfile.txt", "r")
txt <- funcs$file$readlines(fl)  
fl$close()
Marco Sandri
  • 23,289
  • 7
  • 54
  • 58