Pure Programmer
Blue Matrix


Cluster Map

File I/O

L1

This page is under construction. Please come back later.

FileIO1.py
#!/usr/bin/env python3;
###############################################################################
# This program simply copies a file to the console character by
# character like the Unix 'cat' program.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def readTextFile(filespec) :
	ifh = open(filespec, "r", encoding="utf8")
	c = Utils.getchar(ifh)
	while c != None :
		print(chr(c), end="")
		c = Utils.getchar(ifh)
	ifh.close()

# Begin Main
if (len(sys.argv) != 2) :
	print("Syntax: " + sys.argv[0] + " {filename}")
	sys.exit(1)
filespec = sys.argv[1]
try :
	readTextFile(filespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python FileIO1.py ../../data/text/GettysburgAddress.txt Lincoln's Gettysburg Address, given November 19, 1863 on the battlefield near Gettysburg, Pennsylvania, USA Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate-we can not consecrate-we can not hallow-this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us-that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion-that we here highly resolve that these dead shall not have died in vain-that this nation, under God, shall have a new birth of freedom-and that government of the people, by the people, for the people, shall not perish from the earth. $ python FileIO1.py ../../data/text/UnicodeTest.utf8 Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Vor vier Punkten und sieben Jahren haben unsere Väter auf diesem Kontinent eine neue Nation hervorgebracht, die in Freiheit empfangen wurde und sich dem Vorschlag verschrieben hat, dass alle Menschen gleich geschaffen sind. Τέσσερα σκορ και πριν από επτά χρόνια οι πατέρες μας έφεραν σε αυτή την ήπειρο, ένα νέο έθνος, που σχεδιάστηκε στην Ελευθερία και αφιερώθηκε στην πρόταση ότι όλοι οι άνθρωποι δημιουργούνται ίσοι. أربع نقاط وقبل سبع سنوات قدم آباؤنا في هذه القارة ، أمة جديدة ، تم تصورها في الحرية ، ومكرسة لفرضية أن جميع الرجال خلقوا متساوين. ארבע ציונים ולפני שבע שנים אבותינו הציגו ביבשת זו, אומה חדשה, שהגתה בחירות, והוקדשה לטענה שכל הגברים נוצרים שווים. ... Graphemes that take two codepoints Canada 🇨🇦 China 🇨🇳 France 🇫🇷 Greece 🇬🇷 Israel 🇮🇱 Japan 🇯🇵 Mexico 🇲🇽 UK 🇬🇧 US 🇺🇸
FileIO2.py
#!/usr/bin/env python3;
###############################################################################
# This program simply copies a file to the console line by line.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def readTextFile(filespec) :
	ifh = open(filespec, "r", encoding="utf8")
	line = Utils.getline(ifh)
	while line != None :
		print(line)
		line = Utils.getline(ifh)
	ifh.close()

# Begin Main
if (len(sys.argv) != 2) :
	print("Syntax: " + sys.argv[0] + " {filename}")
	sys.exit(1)
filespec = sys.argv[1]
try :
	readTextFile(filespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python FileIO2.py ../../data/text/GettysburgAddress.txt Lincoln's Gettysburg Address, given November 19, 1863 on the battlefield near Gettysburg, Pennsylvania, USA Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate-we can not consecrate-we can not hallow-this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us-that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion-that we here highly resolve that these dead shall not have died in vain-that this nation, under God, shall have a new birth of freedom-and that government of the people, by the people, for the people, shall not perish from the earth. $ python FileIO2.py ../../data/text/UnicodeTest.utf8 Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Vor vier Punkten und sieben Jahren haben unsere Väter auf diesem Kontinent eine neue Nation hervorgebracht, die in Freiheit empfangen wurde und sich dem Vorschlag verschrieben hat, dass alle Menschen gleich geschaffen sind. Τέσσερα σκορ και πριν από επτά χρόνια οι πατέρες μας έφεραν σε αυτή την ήπειρο, ένα νέο έθνος, που σχεδιάστηκε στην Ελευθερία και αφιερώθηκε στην πρόταση ότι όλοι οι άνθρωποι δημιουργούνται ίσοι. أربع نقاط وقبل سبع سنوات قدم آباؤنا في هذه القارة ، أمة جديدة ، تم تصورها في الحرية ، ومكرسة لفرضية أن جميع الرجال خلقوا متساوين. ארבע ציונים ולפני שבע שנים אבותינו הציגו ביבשת זו, אומה חדשה, שהגתה בחירות, והוקדשה לטענה שכל הגברים נוצרים שווים. ... Graphemes that take two codepoints Canada 🇨🇦 China 🇨🇳 France 🇫🇷 Greece 🇬🇷 Israel 🇮🇱 Japan 🇯🇵 Mexico 🇲🇽 UK 🇬🇧 US 🇺🇸
FileIO3.py
#!/usr/bin/env python3;
###############################################################################
# This program reads bytes from a file and prints them in decimal format.
# 
# Copyright © 2021 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def readBinaryFile(filespec) :
	ifh = open(filespec, "rb")
	count = 0
	c = Utils.getbyte(ifh)
	while c != None :
		print(str(c) + " ", end="")
		count += 1
		if (count % 20 == 0) :
			print()
		c = Utils.getbyte(ifh)
	if (count % 20 != 0) :
		print()
	ifh.close()

# Begin Main
if (len(sys.argv) != 2) :
	print("Syntax: " + sys.argv[0] + " {filename}")
	sys.exit(1)
filespec = sys.argv[1]
try :
	readBinaryFile(filespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python FileIO3.py ../../data/text/GettysburgAddress.txt 76 105 110 99 111 108 110 39 115 32 71 101 116 116 121 115 98 117 114 103 32 65 100 100 114 101 115 115 44 32 103 105 118 101 110 32 78 111 118 101 109 98 101 114 32 49 57 44 32 49 56 54 51 10 111 110 32 116 104 101 32 98 97 116 116 108 101 102 105 101 108 100 32 110 101 97 114 32 71 101 116 116 121 115 98 117 114 103 44 32 80 101 110 110 115 121 108 118 97 110 105 97 44 32 85 83 65 10 10 70 111 117 114 32 115 99 111 114 101 32 97 110 100 32 115 101 118 101 110 32 121 101 97 114 115 32 97 103 111 32 111 117 114 32 102 97 116 104 101 114 115 32 98 114 111 117 103 104 116 32 102 111 114 116 104 32 111 110 32 116 104 105 115 32 99 111 110 116 105 110 101 110 116 44 32 97 32 110 101 119 32 110 97 116 105 111 110 44 32 99 ... 110 111 116 32 104 97 118 101 32 100 105 101 100 32 105 110 32 118 97 105 110 45 116 104 97 116 32 116 104 105 115 32 110 97 116 105 111 110 44 32 117 110 100 101 114 32 71 111 100 44 32 115 104 97 108 108 32 104 97 118 101 32 97 32 110 101 119 32 98 105 114 116 104 32 111 102 32 102 114 101 101 100 111 109 45 97 110 100 32 116 104 97 116 32 103 111 118 101 114 110 109 101 110 116 32 111 102 32 116 104 101 32 112 101 111 112 108 101 44 32 98 121 32 116 104 101 32 112 101 111 112 108 101 44 32 102 111 114 32 116 104 101 32 112 101 111 112 108 101 44 32 115 104 97 108 108 32 110 111 116 32 112 101 114 105 115 104 32 102 114 111 109 32 116 104 101 32 101 97 114 116 104 46 10 $ python FileIO3.py ../../data/text/UnicodeTest.utf8 70 111 117 114 32 115 99 111 114 101 32 97 110 100 32 115 101 118 101 110 32 121 101 97 114 115 32 97 103 111 32 111 117 114 32 102 97 116 104 101 114 115 32 98 114 111 117 103 104 116 32 102 111 114 116 104 32 111 110 32 116 104 105 115 32 99 111 110 116 105 110 101 110 116 44 32 97 32 110 101 119 32 110 97 116 105 111 110 44 32 99 111 110 99 101 105 118 101 100 32 105 110 32 76 105 98 101 114 116 121 44 32 97 110 100 32 100 101 100 105 99 97 116 101 100 32 116 111 32 116 104 101 32 112 114 111 112 111 115 105 116 105 111 110 32 116 104 97 116 32 97 108 108 32 109 101 110 32 97 114 101 32 99 114 101 97 116 101 100 32 101 113 117 97 108 46 10 10 86 111 114 32 118 105 101 114 32 80 117 110 107 116 101 110 32 117 110 100 32 115 ... 188 32 61 32 117 204 136 10 237 149 156 32 61 32 225 132 146 225 133 161 225 134 171 10 10 71 114 97 112 104 101 109 101 115 32 116 104 97 116 32 116 97 107 101 32 116 119 111 32 99 111 100 101 112 111 105 110 116 115 10 67 97 110 97 100 97 32 240 159 135 168 240 159 135 166 10 67 104 105 110 97 32 240 159 135 168 240 159 135 179 10 70 114 97 110 99 101 32 240 159 135 171 240 159 135 183 10 71 114 101 101 99 101 32 240 159 135 172 240 159 135 183 10 73 115 114 97 101 108 32 240 159 135 174 240 159 135 177 10 74 97 112 97 110 32 240 159 135 175 240 159 135 181 10 77 101 120 105 99 111 32 240 159 135 178 240 159 135 189 10 85 75 32 240 159 135 172 240 159 135 167 10 85 83 32 240 159 135 186 240 159 135 184 32 10
FileIO4.py
#!/usr/bin/env python3;
###############################################################################
# This program simply writes characters from the alphabet to a file.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def writeTextFile(filespec) :
	ofh = open(filespec, "w", encoding="utf8")
# Latin alphabet
	for c in range(0x41, 0x5A + 1) :
		print(chr(c), file=ofh, end="")
	print("\n", file=ofh, end="")
# Greek alphabet
	for c in range(0x391, 0x3A9 + 1) :
		print(chr(c), file=ofh, end="")
# Cyrillic alphabet
	for c in range(0x410, 0x42F + 1) :
		print(chr(c), file=ofh, end="")
	print("\n", file=ofh, end="")
# Katakana alphabet
	for c in range(0x30A0, 0x30FF + 1) :
		print(chr(c), file=ofh, end="")
	print("\n", file=ofh, end="")
	ofh.close()

# Begin Main
if (len(sys.argv) != 2) :
	print("Syntax: " + sys.argv[0] + " {filename}")
	sys.exit(1)
filespec = sys.argv[1]
try :
	writeTextFile(filespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python3 FileIO4.py output/testFileIO4.txt $ cat output/testFileIO4.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽヾヿ
FileIO5.py
#!/usr/bin/env python3;
###############################################################################
# This program simply writes lines with the alphabet to a file.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def writeTextFile(filespec) :
	ofh = open(filespec, "w", encoding="utf8")
	print("ABCDEFGHIJKLMNOPQRSTUVWXYZ", file=ofh, end="\n")
	print("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ", file=ofh, end="\n")
	print("АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ", file=ofh, end="\n")
	print("゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタ", file=ofh, end="\n")
	print("ダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ", file=ofh, end="\n")
	print("ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽヾヿ", file=ofh, end="\n")
	ofh.close()

# Begin Main
if (len(sys.argv) != 2) :
	print("Syntax: " + sys.argv[0] + " {filename}")
	sys.exit(1)
filespec = sys.argv[1]
try :
	writeTextFile(filespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python3 FileIO5.py output/testFileIO5.txt $ cat output/testFileIO5.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタ ダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽヾヿ
FileIO6.py
#!/usr/bin/env python3;
###############################################################################
# This program simply writes the bytes 0 - 256 to a binary file.
# 
# Copyright © 2021 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def writeBinaryFile(filespec) :
	ofh = open(filespec, "wb")
	for b in range(0, 255 + 1) :
		ofh.write(b.to_bytes(1, byteorder='big', signed=False))
	ofh.close()

# Begin Main
if (len(sys.argv) != 2) :
	print("Syntax: " + sys.argv[0] + " {filename}")
	sys.exit(1)
filespec = sys.argv[1]
try :
	writeBinaryFile(filespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python3 FileIO6.py output/testFileIO6.bin $ od -t x1 output/testFileIO6.bin 0000000 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 0000020 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 0000040 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 0000060 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f 0000100 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 0000120 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f 0000140 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 0000160 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f 0000200 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f 0000220 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f 0000240 a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af 0000260 b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf 0000300 c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf 0000320 d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df 0000340 e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef 0000360 f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff 0000400
FileIO7.py
#!/usr/bin/env python3;
###############################################################################
# This program simply copies one file to another, character by
# character like the Unix 'cat' program.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def copyTextFile(fromFilespec, toFilespec) :
	ifh = open(fromFilespec, "r", encoding="utf8")
	ofh = open(toFilespec, "w", encoding="utf8")
	c = Utils.getchar(ifh)
	while c != None :
		print(chr(c), file=ofh, end="")
		c = Utils.getchar(ifh)
	ifh.close()
	ofh.close()

# Begin Main
if (len(sys.argv) != 3) :
	print("Syntax: " + sys.argv[0] + " {fromFilespec} {toFilespec}")
	sys.exit(1)
fromFilespec = sys.argv[1]
toFilespec = sys.argv[2]
try :
	copyTextFile(fromFilespec, toFilespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python3 FileIO7.py ../../data/text/GettysburgAddress.txt output/testFileIO7.txt $ diff -q ../../data/text/GettysburgAddress.txt output/testFileIO7.txt $ python3 FileIO7.py ../../data/text/UnicodeTest.utf8 output/testFileIO7.utf8 $ diff -q ../../data/text/UnicodeTest.utf8 output/testFileIO7.utf8
FileIO8.py
#!/usr/bin/env python3;
###############################################################################
# This program simply copies one file to another, line by line.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def copyTextFile(fromFilespec, toFilespec) :
	ifh = open(fromFilespec, "r", encoding="utf8")
	ofh = open(toFilespec, "w", encoding="utf8")
	line = Utils.getline(ifh)
	while line != None :
		print(line, file=ofh, end="\n")
		line = Utils.getline(ifh)
	ifh.close()
	ofh.close()

# Begin Main
if (len(sys.argv) != 3) :
	print("Syntax: " + sys.argv[0] + " {fromFilespec} {toFilespec}")
	sys.exit(1)
fromFilespec = sys.argv[1]
toFilespec = sys.argv[2]
try :
	copyTextFile(fromFilespec, toFilespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python3 FileIO8.py ../../data/text/GettysburgAddress.txt output/testFileIO8.txt $ diff -q ../../data/text/GettysburgAddress.txt output/testFileIO8.txt $ python3 FileIO8.py ../../data/text/UnicodeTest.utf8 output/testFileIO8.utf8 $ diff -q ../../data/text/UnicodeTest.utf8 output/testFileIO8.utf8
FileIO9.py
#!/usr/bin/env python3;
###############################################################################
# This program reads bytes from a binary file and copies them to another file.
# 
# Copyright © 2021 Richard Lesh.  All rights reserved.
###############################################################################

import Utils
import sys

def copyBinaryFile(fromFilespec, toFilespec) :
	ifh = open(fromFilespec, "rb")
	ofh = open(toFilespec, "wb")
	c = Utils.getbyte(ifh)
	while c != None :
		ofh.write(c.to_bytes(1, byteorder='big', signed=False))
		c = Utils.getbyte(ifh)
	ifh.close()
	ofh.close()

# Begin Main
if (len(sys.argv) != 3) :
	print("Syntax: " + sys.argv[0] + " {fromFilespec} {toFilespec}")
	sys.exit(1)
fromFilespec = sys.argv[1]
toFilespec = sys.argv[2]
try :
	copyBinaryFile(fromFilespec, toFilespec)
except OSError as ex :
	print("Error: " + str(ex))

Output
$ python3 FileIO9.py ../../data/text/GettysburgAddress.txt output/testFileIO9.txt $ diff -q ../../data/text/GettysburgAddress.txt output/testFileIO9.txt $ python3 FileIO9.py ../../data/text/UnicodeTest.utf8 output/testFileIO9.utf8 $ diff -q ../../data/text/UnicodeTest.utf8 output/testFileIO9.utf8 $ python3 FileIO9.py ../../data/images/GlowingCat.jpg output/testFileIO9.jpg $ diff -q ../../data/images/GlowingCat.jpg output/testFileIO9.jpg
python

Questions

Projects

More ★'s indicate higher difficulty level.

References