CONVERSION REFERENCE
Convert whole-file UTF-8 reads and writes with the forms below. Keep one read or write operation in each with statement.
Conversion itself does not open these paths. File access happens when you later compile and run the generated C.
with open(path, 'r', encoding='utf-8', newline='') as handle:
...
Use literal mode 'r' or 'w', encoding 'utf-8', and newline ''. Keep the with directly inside a function, outside any branch or loop. Give the handle a fresh name and let the with close it.
def load(path: str) -> str:
with open(path, 'r', encoding='utf-8', newline='') as handle:
return handle.read()
You may instead assign to a fresh local and return it immediately after the with:
def load_named(path: str) -> str:
with open(path, 'r', encoding='utf-8', newline='') as handle:
content = handle.read()
return content
The default read limit is 1 MiB (1,048,576 bytes). Files must contain valid UTF-8 without embedded NUL bytes. Sized reads, readline, and processing or aliasing the read result inside the converted function are unsupported.
def save(path: str, text: str) -> int:
with open(path, 'w', encoding='utf-8', newline='') as handle:
handle.write(text)
return 0
The write argument must be a string variable or literal. The write result is discarded. The generated C writes the supplied UTF-8 bytes without newline conversion. Mode 'w' creates or truncates the destination when the generated program runs.
def save_two(first: str, second: str, text: str) -> int:
with open(first, 'w', encoding='utf-8', newline='') as left:
left.write(text)
with open(second, 'w', encoding='utf-8', newline='') as right:
right.write(text)
return 0
Use separate sequential with statements. Ordinary supported code may appear before or after them.
with.close().with.write.PYC3905 identifies an unsupported read/write operation or result use. Literal NUL text can also produce PYC4503. See file diagnostics.
A generated function that accesses a file receives an additional final parameter, int64_t *pycf_status. Pass a pointer to a writable integer and check it after the call. Use the function's generated declaration for its exact name and argument order.
| Status | Meaning | What to do |
|---|---|---|
| 0 | Success | Use the result; release a successful read buffer when finished. |
| 1 | Could not open the file | Check the path and permissions. |
| 2 | Could not allocate memory | Reduce memory demand or handle the failure in the caller. |
| 3 | Read failed | Do not use the read result. |
| 4 | Read limit exceeded | Use a smaller file or an appropriate supported read limit. |
| 5 | File contains NUL bytes | Use NUL-free text input. |
| 6 | File is not valid UTF-8 | Convert the file's encoding before calling the function. |
| 7 | Closing the file failed | Treat the operation as failed. |
| 8 | Write failed | Check the destination and available storage; a partial write may remain. |
char * is allocated with malloc. Release it exactly once with free after use.