Difference between revisions of "Code Snippet: Print a File Line-by-Line"
From Coder Merlin
(Created page with "== Swift == <syntaxhighlight lang="swift"> import Foundation // Determine the file name let filename = "main.swift" // Read the contents of the specified file let contents =...") |
(Added Python example) |
||
Line 20: | Line 20: | ||
lineNumber += 1 | lineNumber += 1 | ||
} | } | ||
</syntaxhighlight> | |||
== Python == | |||
<syntaxhighlight lang="python"> | |||
file_path = 'main.py' | |||
print(f'Loading {file_path}...') | |||
try: | |||
with open(file_path, 'r') as file: | |||
linenumber = 1 | |||
for line in file: | |||
print(f'{linenumber}: {line.rstrip()}') | |||
linenumber += 1 | |||
except Exception as e: | |||
print(e) | |||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 00:44, 27 January 2020
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Swift[edit]
import Foundation
// Determine the file name
let filename = "main.swift"
// Read the contents of the specified file
let contents = try! String(contentsOfFile: filename)
// Split the file into separate lines
let lines = contents.split(separator:"\n")
// Define a variable to track the current line number
// Iterate over each line and print the line preceded
// by the line number
var lineNumber = 1
for line in lines {
print("\(lineNumber): \(line)")
lineNumber += 1
}
Python[edit]
file_path = 'main.py'
print(f'Loading {file_path}...')
try:
with open(file_path, 'r') as file:
linenumber = 1
for line in file:
print(f'{linenumber}: {line.rstrip()}')
linenumber += 1
except Exception as e:
print(e)