Difference between revisions of "Code Snippet: Read File"

From Coder Merlin
Line 6: Line 6:


let contents = try! String(contentsOfFile: "hello.txt")                                                                                                                                               
let contents = try! String(contentsOfFile: "hello.txt")                                                                                                                                               
</syntaxhighlight>
Better:
<syntaxhighlight lang="swift">
        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).")
        }
</syntaxhighlight>
</syntaxhighlight>


== Python ==
== Python ==

Revision as of 22:40, 1 April 2019

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]