$ cat input.txt
First line.
Second line.
Last line.
| (1) read the whole content to a string
|
f = open("input.txt", "r")
content = f.read()
f.close()
print("'" + content + "'")
|
let content = readFile("input.txt")
echo "'" & content & "'"
|
Output:
'First line.
Second line.
Last line.
'
| (2) read the whole content to a list/seq
|
f = open("input.txt", "r")
lines = f.read().splitlines()
f.close()
print(lines)
# ['First line.', 'Second line.', 'Last line.']
|
import std/strutils
let v1 = readFile("input.txt").splitlines()
echo v1
# @["First line.", "Second line.", "Last line.", ""]
let v2 = readFile("input.txt").strip().splitlines()
echo v2
# @["First line.", "Second line.", "Last line."]
|
Notice the subtle difference:
- Python: when you use
.splitlines(), at the end of the resulting list there is no empty string.
- Nim: at the end of the seq (v1) there is an empty string. So
.splitlines() must just call .split('\n'). If you don't need that empty string, then combine splitlines() with strip() .
Read just one line
$ cat input.txt
first line
second line
last line
| (3) read just one line
|
f = open("input.txt")
print(f.readline()) # "first line\n"
print(f.readline().rstrip("\n")) # "second line"
f.close()
|
let f = open("input.txt")
echo f.readLine() # "first line"
echo f.readLine() # "second line"
f.close()
|
Very similar. The only difference: Python keeps the trailing newline, while Nim removes it.