Code Snippet: Read File

From Coder Merlin
Revision as of 00:48, 27 January 2020 by Yarsenius (talk | contribs) (Added Python example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Read the contents of a file into a string[edit]

Swift[edit]

import Foundation

let contents = try! String(contentsOfFile: "hello.txt")

Better:

let filePath = "~/example.csv"
let fileURL = URL(fileURLWithPath:filePath.expandingTildeInPath)

print("Loading \(filePath)...")
do {
    let contents = try String(contentsOf: fileURL)
    for line in contents.components(separatedBy:"\n") {
        print(line)
    }
} catch {
    print("Failed to load due to error \(error).")
}

Python[edit]

file_path = '~/example.csv'
print(f'Loading {file_path}...')

try:
    with open(file_path, 'r') as file:
        contents = file.read()
        # Do something with contents
except Exception as e:
    print(e)