File System
Some internal Pyodide file system methods are exposed.
For more info, see the API reference docs.
import { usePython } from 'react-py'
function Codeblock() {
const { readFile, writeFile, mkdir, rmdir ... } = usePython()
function read() {
const file = readFile('/hello.txt')
console.log(file)
}
function write() {
const data = 'hello world!'
writeFile('/hello.txt', data)
}
function createDir() {
mkdir('lib')
}
function deleteDir() {
rmdir('cruft')
}
...
}
You can also use Python to read and write files:
Setting up environment...
with open("hello.txt", "w") as f:
f.write('hello world!')
with open('hello.txt') as f:
contents = f.read()
print(contents)
note
Files are not shared between instances, each usage of the usePython
hook has an independent file system. Files are also not persisted on page reload.
Using multiple files
You can use Custom Modules to make use of multiple files:
Setting up environment...
from numbers import multiply
from strings import reverse_string
numbers = [1, 2, 3, 4, 5]
result = multiply(numbers)
print("Result of multiplication:", result)
string_to_reverse = "Hello, World!"
reversed_string = reverse_string(string_to_reverse)
print("Reversed string:", reversed_string)
You can find the source code for this example here.