0% found this document useful (0 votes)
12 views

python input and output

The document contains Python scripts that define various functions for file handling, including reading, writing, appending, and JSON serialization/deserialization. It also includes a Student class with methods for JSON representation and attribute management. Additionally, there are scripts for appending text to files and computing metrics from standard input.

Uploaded by

Desalegn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

python input and output

The document contains Python scripts that define various functions for file handling, including reading, writing, appending, and JSON serialization/deserialization. It also includes a Student class with methods for JSON representation and attribute management. Additionally, there are scripts for appending text to files and computing metrics from standard input.

Uploaded by

Desalegn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

https://www.youtube.

com/@Randommall/videos
0x0B-python-input_output/0-read_file.py

#!/usr/bin/python3

"""Defines a text file-reading function."""

def read_file(filename=""):
"""Print the contents of a UTF8 text file to stdout."""
with open(filename, encoding="utf-8") as f:
print(f.read(), end="")

0x0B-python-input_output/1-write_file.py

#!/usr/bin/python3

"""Defines a file-writing function."""

def write_file(filename="", text=""):


"""Write a string to a UTF8 text file.
Args:
filename (str): The name of the file to write.
text (str): The text to write to the file.
Returns:
The number of characters written.
"""
with open(filename, "w", encoding="utf-8") as f:
return f.write(text)

0x0B-python-input_output/2-append_write.py

#!/usr/bin/python3

"""Defines a file-appending function."""

def append_write(filename="", text=""):


"""Appends a string to the end of a UTF8 text file.
Args:
filename (str): The name of the file to append to.
text (str): The string to append to the file.
Returns:
The number of characters appended.
"""
with open(filename, "a", encoding="utf-8") as f:
return f.write(text)

0x0B-python-input_output/3-to_json_string.py

#!/usr/bin/python3

"""Defines a string-to-JSON function."""


import json

def to_json_string(my_obj):
"""Return the JSON representation of a string object."""
return json.dumps(my_obj)

0x0B-python-input_output/4-from_json_string.py

#!/usr/bin/python3

"""Defines a JSON-to-object function."""


import json

def from_json_string(my_str):
"""Return the Python object representation of a JSON string."""
return json.loads(my_str)

0x0B-python-input_output/5-save_to_json_file.py

#!/usr/bin/python3

"""Defines a JSON file-writing function."""


import json

def save_to_json_file(my_obj, filename):


"""Write an object to a text file using JSON representation."""
with open(filename, "w") as f:
json.dump(my_obj, f)

0x0B-python-input_output/6-load_from_json_file.py

#!/usr/bin/python3

"""Defines a JSON file-reading function."""


import json

def load_from_json_file(filename):
"""Create a Python object from a JSON file."""
with open(filename) as f:
return json.load(f)

0x0B-python-input_output/7-add_item.py

#!/usr/bin/python3

"""Add all arguments to a Python list and save them to a file."""

import sys

if __name__ == "__main__":
save_to_json_file = __import__('7-save_to_json_file').save_to_json_file
load_from_json_file = \
__import__('8-load_from_json_file').load_from_json_file

try:
items = load_from_json_file("add_item.json")
except FileNotFoundError:
items = []
items.extend(sys.argv[1:])
save_to_json_file(items, "add_item.json")

0x0B-python-input_output/8-class_to_json.py

#!/usr/bin/python3

"""Defines a Python class-to-JSON function."""


def class_to_json(obj):
"""Return the dictionary represntation of a simple data structure."""
return obj.__dict__

0x0B-python-input_output/9-student.py

#!/usr/bin/python3

"""Defines a class Student."""

class Student:
"""Represent a student."""

def __init__(self, first_name, last_name, age):


"""Initialize a new Student.
Args:
first_name (str): The first name of the student.
last_name (str): The last name of the student.
age (int): The age of the student.
"""
self.first_name = first_name
self.last_name = last_name
self.age = age

def to_json(self):
"""Get a dictionary representation of the Student."""
return self.

0x0B-python-input_output/10-student.py

#!/usr/bin/python3

"""Defines a class Student."""

class Student:
"""Represent a student."""

def __init__(self, first_name, last_name, age):


"""Initialize a new Student.
Args:
first_name (str): The first name of the student.
last_name (str): The last name of the student.
age (int): The age of the student.
"""
self.first_name = first_name
self.last_name = last_name
self.age = age

def to_json(self, attrs=None):


"""Get a dictionary representation of the Student.
If attrs is a list of strings, represents only those attributes
included in the list.
Args:
attrs (list): (Optional) The attributes to represent.
"""
if (type(attrs) == list and
all(type(element) == str for element in attrs)):
return {k: getattr(self, k) for k in attrs if hasattr(self, k)}
return self.__dict__

0x0B-python-input_output/100-append_after.py

#!/usr/bin/python3

"""Defines a text file insertion function."""

def append_after(filename="", search_string="", new_string=""):


"""Insert text after each line containing a given string in a file.
Args:
filename (str): The name of the file.
search_string (str): The string to search for within the file.
new_string (str): The string to insert.
"""
text = ""
with open(filename) as r:
for line in r:
text += line
if search_string in line:
text += new_string
with open(filename, "w") as w:
w.write(text)
0x0B-python-input_output/101-stats.py

#!/usr/bin/python3

"""Reads from standard input and computes metrics.


After every ten lines or the input of a keyboard interruption (CTRL + C),
prints the following statistics:
- Total file size up to that point.
- Count of read status codes up to that point.
"""

def print_stats(size, status_codes):


"""Print accumulated metrics.
Args:
size (int): The accumulated read file size.
status_codes (dict): The accumulated count of status codes.
"""
print("File size: {}".format(size))
for key in sorted(status_codes):
print("{}: {}".format(key, status_codes[key]))

if __name__ == "__main__":
import sys

size = 0
status_codes = {}
valid_codes = ['200', '301', '400', '401', '403', '404', '405', '500']
count = 0

try:
for line in sys.stdin:
if count == 10:
print_stats(size, status_codes)
count = 1
else:
count += 1

line = line.split()

try:
size += int(line[-1])
except (IndexError, ValueError):
pass
try:
if line[-2] in valid_codes:
if status_codes.get(line[-2], -1) == -1:
status_codes[line[-2]] = 1
else:
status_codes[line[-2]] += 1
except IndexError:
pass

print_stats(size, status_codes)

except KeyboardInterrupt:
print_stats(size, status_codes)
raise

0x0B-python-input_output/11-student.py

#!/usr/bin/python3

"""Defines a class Student."""

class Student:
"""Represent a student."""

def __init__(self, first_name, last_name, age):


"""Initialize a new Student.
Args:
first_name (str): The first name of the student.
last_name (str): The last name of the student.
age (int): The age of the student.
"""
self.first_name = first_name
self.last_name = last_name
self.age = age

def to_json(self, attrs=None):


"""Get a dictionary representation of the Student.
If attrs is a list of strings, represents only those attributes
included in the list.
Args:
attrs (list): (Optional) The attributes to represent.
"""
if (type(attrs) == list and
all(type(ele) == str for ele in attrs)):
return {k: getattr(self, k) for k in attrs if hasattr(self, k)}
return self.__dict__

def reload_from_json(self, json):


"""Replace all attributes of the Student.
Args:
json (dict): The key/value pairs to replace attributes with.
"""
for k, v in json.items():
setattr(self, k, v)

You might also like