Solving CS50P - Problem Set 6
Karabo Molefi
3 min read
In this Problem Set we explore File I/O (input/output), which is the ability of a program to take a file as input or create a file as output.
ℹ
Disclaimer: The following code solutions are for educational purposes only and are not intended to be used or submitted as your own. Cheating is a violation of the Academic Honesty of the course. All problem sets presented are owned by Harvard University.
Lines of code
import sys
lines =[]
def main():
file_name = cmd_arg()
if python_file(file_name):
ans = get_lines(file_name)
else:
sys.exit("Not a Python file")
ans = count(ans)
print(ans)
def cmd_arg():
arg = sys.argv
if len(arg) < 2:
sys.exit("Too few command-line arguments")
if len(arg) > 2:
sys.exit("Too many command-line arguments")
else:
return arg[1]
def python_file(f):
return f.endswith(".py")
def get_lines(f):
try:
file = open(f)
except FileNotFoundError:
sys.exit("File does not exist")
else:
for line in file:
lines.append(line)
return lines
new_lines = []
def count(l):
for line in l:
line = line.strip()
if line.lstrip() == "":
continue
elif line.startswith("#"):
continue
else:
new_lines.append(line)
return len(new_lines)
if __name__ == "__main__":
main()
Pizza Py
import csv
import sys
from tabulate import tabulate
table =[]
def main():
file_name = cmd_arg()
if csv_file(file_name):
table = make_table(file_name)
else:
sys.exit("Not a CSV file")
print(tabulate(table, headers="keys", tablefmt="grid"))
def make_table(f):
try:
file = open(f)
except FileNotFoundError:
sys.exit("File does not exist")
else:
reader = csv.DictReader(file)
for row in reader:
table.append(row)
return table
def cmd_arg():
arg = sys.argv
if len(arg) < 2:
sys.exit("Too few command-line arguments")
if len(arg) > 2:
sys.exit("Too many command-line arguments")
else:
return arg[1]
def csv_file(f):
return f.endswith(".csv")
if __name__ == "__main__":
main()
Scourgify
import sys
import csv
details=[]
def main():
before, after = cmd_arg()
before = convert(before)
after = write(after)
def cmd_arg():
arg = sys.argv
if len(arg) < 3:
sys.exit("Too few command-line arguments")
if len(arg) > 3:
sys.exit("Too many command-line arguments")
else:
return list((arg[1], arg[2]))
def convert(f):
try:
file = open(f)
except IOError:
sys.exit(f"could not read {f}")
else:
reader = csv.reader(file)
for name, house in reader:
name = name.rstrip().split(", ")
first = name[-1]
last = name[0]
details.append(list((first, last, house)))
return details
def write(a):
details.pop(0)
with open(a, "w") as file:
writer = csv.DictWriter(file, fieldnames=["first", "last", "house"])
writer.writeheader()
for d in details:
writer.writerow({"first": d[0], "last": d[1], "house": d[2]})
if __name__ == "__main__":
main()
CS50 P-Shirt
import os
import sys
from PIL import Image, ImageOps
shirt = Image.open("shirt.png")
size = shirt.size
def main():
if valid():
before = sys.argv[1]
after = sys.argv[2]
edit(before, after)
def edit(b,a):
with Image.open(b) as im:
im = ImageOps.fit(im, size)
im.paste(shirt, shirt)
im.save(a)
def valid():
arg1, arg2 = cmd_arg()
if exists(arg1):
if extension(arg1, arg2):
return True
else:
sys.exit("Input and output have different extensions")
else:
sys.exit()
def cmd_arg():
arg = sys.argv
if len(arg) < 3:
sys.exit("Too few command-line arguments")
if len(arg) > 3:
sys.exit("Too many command-line arguments")
else:
return list((arg[1], arg[2]))
def exists(i):
return os.path.isfile(i)
def extension(a, b):
path = os.path.splitext(a)
path2 = os.path.splitext(b)
return path[1] == path2[1]
if __name__ == "__main__":
main()
0
Subscribe to my newsletter
Read articles from Karabo Molefi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by