Skip to content

Instantly share code, notes, and snippets.

@seisvelas
Created May 31, 2021 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seisvelas/cd43a4e52f227ba8892d26f791b87114 to your computer and use it in GitHub Desktop.
Save seisvelas/cd43a4e52f227ba8892d26f791b87114 to your computer and use it in GitHub Desktop.
Teaching Fatima fundamental file operations in Python
# Simple version of cp command
import sys
if len(sys.argv) < 3:
raise Exception('too few arguments')
command, source, destination, *rest = sys.argv
with open(source, 'rb') as source_file:
with open(destination, 'wb') as destination_file:
while current_chunk := source_file.read(4096):
destination_file.write(current_chunk)
# open() - modes: r, w, r+, a, x, b
our_family = open('family.log', 'w')
# write() to file
our_family.write('Khety\n')
our_family.write('Maxwell\n')
our_family.write('????\n')
# close()
our_family.close()
# Reopen, in read mode!
our_family = open('family.log', 'r')
# read()
family = our_family.read()
print(family)
our_family.seek(3)
print(f'here is our family, again: {our_family.read()}')
our_family.close()
# using contexts, it will call close
# at the end of the block
print('use with to not need close()')
with open('family.log', 'r') as famlog:
print(famlog.read())
print('loop through lines')
# loop through lines of a text file
with open('family.log', 'r') as famlog:
for line in famlog:
print(f'current line: {line}')
# read x characters
print('print first x chars')
with open('family.log', 'r') as famlog:
print(famlog.read(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment