fs.open()
Opens a file in the requested mode.
Signature
fs.open(path[, mode])
Parameters
Text path. Mode r (default), w or a. Optional b for binary reads, + for both reading and writing, each at most once.
Returns
VM-owned file handle.
Behavior
w creates or truncates. a creates or appends. r requires an existing file. The handle has a byte cursor.
Errors
Invalid mode/path, missing permission or OS error.
Example
use fs
p = fs.temporary_file()
f = fs.open(p, 'r')
fs.close(f)
fs.remove(p)
Open for reading
Create a temporary file before opening it in the default reading mode.
use fs
path = fs.temporary_file()
try:
write(path, 'Atom')
file = fs.open(path)
try:
print(read(file))
finally:
fs.close(file)
finally:
fs.remove(path)
Atom
The default reads an existing file. Closing the handle does not delete the file.
Open for appending
Use a to add bytes at the end of existing contents.
use fs
path = fs.temporary_file()
try:
write(path, 'Hello')
file = fs.open(path, 'a')
try:
write(file, ', Atom')
finally:
fs.close(file)
print(read(path))
finally:
fs.remove(path)
Hello, Atom
Appending preserves the original text. A w-mode handle would instead truncate it.