How to open text file with open() with specific path?

Hi,

Let us say I have “test.text” in my downloads. Path = "C:\Users\something\Desktop"

How to make my code open this file (using the client code only)

I tried open() method as following:

path = ‘C:\Users\something\Desktop\test.text’
f = open(path)
print(f.read())

I got this error: IOError: [Errno 2] No such file or directory
the directory is correct

when I use path = ‘C:\Users\something\Desktop\test.text’
I got this error: SyntaxError: invalid string (possibly contains a unicode character)

Please explain how to fix this issue.
Thank you

Welcome, @morespacefmx.

There are two issues here. First, there’s the backslashes (\ characters). In a normal Python string, a backslash changes the interpretation of the following character. This lets you write a tab character as ‘\t’, or a newline as ‘\n’. See https://docs.python.org/3.7/tutorial/introduction.html#strings . Look for “raw strings”.

The second issue is related to security. Specifically, to the security of the files on your (and everyone else’s) computer. Python code running in an Anvil page is not running inside a “normal” Python interpreter on your computer. It is running inside your web browser.

Do you want someone else’s code, running in your browser, to be able to read any file it wants, anywhere in your computer? Or even just your personal files?

Probably not. For this reason, a browser simply does not have access to its choice of files. It has access to files that were provided as part of the web page or web site, but other files, located on your computer, are off-limits by default.

To get a normally-off-limits file, e.g., for upload, it must ask for your permission. Even then, it doesn’t get the file it chooses. You choose the file, or nothing at all, if you reject the request. So your files are (relatively) safe from “rogue” webpage programs.

If you want to use Python’s open() to read files of your program’s choosing, anywhere on your computer, you can. Just do it in a regular Python interpreter, running on your own computer.

If you want to read a file on your computer, in an Anvil app (which runs in your browser), then you use a FileLoader instead. It will prompt you to “upload” the file. It is a much more indirect method, but it works within your browser’s security scheme.

There are lots of examples in Anvil’s Learning Center, and in this forum. Just search for “FileLoader”, and you’ll have plenty of examples to follow.

Thanks, and welcome aboard!

5 Likes