I am new to Python/pyscript/html. I want to create an interactive dashboard using Python, based on csv/text or json files which are on my local drive. The HTML file works and I am able to access it via localhost.
The issue I have is with this part: <py-script src="test.py"> </py-script>
If the test.py contains print(test)
it will print test. But if the test.py contains df = pd.read_csv(r'U:\df.csv', sep='\t')
it doesn't work. Even though the py works in a normal python environment.
The error code is FileNotFoundError: [Errno 44] No such file or directory: 'U:\\df.json'
. I noticed that it creates another backslash. I have changed the location of the file, but nothing seems to work.
I even added the logic straight into the py-script, but this does not work either.
<body>
<py-script >
import pandas as pd
Output12 = pd.read_csv(r'U:\Project\df.csv', sep='\t') </py-script>
</body>
Hope this makes sense.
When PyScript (or any system using the Pyodide runtime) accesses files with something like with open(...)
, the filesystem it's accessing is the virtual, in-memory filesystem that that Emscripten wraps a program with at compilation time, not your local filesystem. This filesystem is reset/bootstrapped from scratch each time the page loads, and lives in the Browser tab's memory.
To load files into the virtual filesystem, PyScript provides a feature of the <py-config> tag called [[fetch]] configurations. A fetch configuration contains a files
key, which is a list of files to load into the current working directory of the file system (the same folder py-script tags run in).
Assuming that your localhost server uses D:/project
as the root, you can load into the virtual file system like so:
<body>
<py-config>
[[fetch]]
files = ['df.csv'] # This is a relative URL; you can also use a fully qualified URL
</py-config>
<py-script >
import pandas as pd
Output12 = pd.read_csv('df.csv', sep='\t')
</py-script>
</body>
A [[fetch]]
configuration can take several additional keys, including from
for introducing a general prefix to all the fetched file paths, to_file
for specifying a filename that's different from the file being loaded, and to_folder
for specifying a different folder in the virtual filesystem to load to. See the linked docs above for more info and examples.