This tutorial explains multiple examples of files.
How to read a file in Nim
Suppose, you have a file test.txt
that contains the following content.
one
two
three
Let’s see an example to read file content.
The readFile()
procedure reads the entire file content into a string variable.
try:
let str = readFile("test.txt")
echo str
except:
console.log("Unable to read a file")
If the file is large, it is not good to read the entire file content into a string. It is better to read line by line.
Here is an example to read file line by line
- create file stream using the
open
method - use the
readLine()
method to read file line by line - print the line
- when you are done with file reading, you have to close the file stream using the
defer
andclose
method
try:
let file = open("test.txt")
defer: file.close()
let line = file.readLine()
echo line
except:
console.log("Unable to read a file")
How to write a file in Nim with an example
This is an example of writing a string into a file.
try:
let
fileName = "/example/test.txt"
str = "one two three"
writeFile(fileName, str)
except:
console.log("Unable to write a file")