Python Classroom Series – 07/Sept/2021

Data in Python

  • An active program accesses data store in RAM. RAM is very fast but volatile. Once the application is closed and relaunched we need to allocate the memory.
  • So if the application which we are developing requires data to be stored we will be using files/databases
  • Lets get started with files
    • Flat text files
    • Padded text files
    • Tabular text files
    • csv files
    • XML
    • JSON
    • YAML

Python File I/O

  • Python has a built in open function to open the file which returns a file object called as handle, which can be used to read or modify the file accordingly
  • while opening the file we can specify the mode of opening
    • r: opening a file for reading
    • w: opening a file for writing
    • x: open a file for writing but exclusively create a files, if the file already exists the operation fails
    • a: Open the file for adding content to the end of the file, if the file doesn’t exist then it is created
    • t: opens a file in text
    • b: opens the file in binary
    • +: opens a file for updating (reading and writing)
  • We have a method called as close() to close the file handle which free’s up resources
f = open('test.txt')
#perform some operations 
  • Alternative to this is
    f = open('test.txt')
    #perform file operations
  • Best approach is to use the with block, where there is no need to explicity call close as once the code block is executd the close() is done/called automatically
with open('test.txt') as f:
    # perform operations
  • Lets write a sample to write files in python

def write_demo():
    with open("data/test.txt", "w", encoding="utf-8") as f:
        f.write("first line \n")
        f.write("second line \n")
        f.write("third line \n")

def append_demo():
    with open("data/test.txt", "a", encoding="utf-8") as f:
        f.write('some lines from append')

def read_demo():
    with open("data/test.txt", "r", encoding="utf-8") as f:
        for item in f.readlines():

if __name__ == '__main__':

CSV Files

  • Delimited files are often used as an exchange format for spreatsheets and databases.
  • You can read CSV files manually, a line at a time splitting into fields at comma sperators
  • Refer Here to understand what csv is
  • Lets write a simple program to store the results in csv file
  • For working with csv we have standard libarary which is csv Refer Here
  • Sample CSV code to write and read from csv
import csv
def is_prime(number: int):
    for index in range(2, number//2 + 1):
        if number%index == 0:
            return False
    return True

def write_to_csv(number: int, result: bool):
    with open('data/prime.csv', 'at') as csv_file:
        prime_writer = csv.writer(csv_file)        
        prime_writer.writerow([number, result])

def read_from_csv():
    with open('data/prime.csv', 'rt') as csv_file:
        prime_reader = csv.reader(csv_file)
        results_dict = dict()
        for row in prime_reader:
            if len(row) !=2:
            results_dict[int(row[0])] = bool(row[1])
        return results_dict


if __name__ == '__main__':
    results_dict = read_from_csv()
    number = int(input('Enter the number: '))
    if number in results_dict:
        result = is_prime(number)
        write_to_csv(number, result)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin