File System
Stable
File system functions are stable in Levython 1.0.
Levython provides built-in functions for reading, writing, and checking files.
Table of Contents
read_file(path)#
Read the entire contents of a file as a string.
read_file(path: string) -> string
-
path
string
Path to the file to read
levython
content <- read_file("data.txt")
say(content)
write_file(path, content)#
Write a string to a file. Creates the file if it doesn't exist, overwrites if it does.
write_file(path: string, content: string) -> null
-
path
string
Path to the file to write
-
content
string
Content to write to the file
levython
write_file("output.txt", "Hello, World!")
say("File written successfully")
file_exists(path)#
Check if a file exists at the given path.
file_exists(path: string) -> boolean
-
path
string
Path to check
levython
if file_exists("config.txt") {
say("Config file found")
config <- read_file("config.txt")
} else {
say("Config file not found, using defaults")
}
Examples#
Read and Process a File
levython
# Read file and count characters
content <- read_file("document.txt")
char_count <- len(content)
say("Character count: " + str(char_count))
Save Program Output
levython
# Generate and save report
report <- "Levython Report\n"
report <- report + "===============\n"
report <- report + "Status: OK\n"
report <- report + "Version: 1.0\n"
write_file("report.txt", report)
say("Report saved to report.txt")
Safe File Reading
levython
act read_safe(path) {
if file_exists(path) {
-> read_file(path)
}
-> ""
}
data <- read_safe("optional.txt")
if len(data) > 0 {
say("File content: " + data)
} else {
say("File is empty or doesn't exist")
}