File Handling in Python

Sept. 24, 2022, 11:15 a.m.


...

A file is basically used because real life applications involve large amounts of data and in such situations we cannot expect those data to be stored in a variable.

In order to use files, we have to learn file input and output operation, that is, how data is read or written to a file. We first open a file, read or write to it, and then finally close it.

A file is basically used because real life applications involve large amounts of data and in such situations we cannot expect those data to be stored in a variable.

In order to use files, we have to learn file input and output operation, that is, how data is read or written to a file. We first open a file, read or write to it, and then finally close it.

File access modes:

r This is the default mode of opening a file for reading only.

rb Reading only in binary format.

r+ Reading and writing.

rb+ Reading and writng in binary format.

w writing only

wb writing in binary format.

w+ writing and reading.

wb+ writing and reading in binary format

a appending

ab appending in binary format.

a+ appending and reading

ab+ appending and reading in binary format.

Open a file in read mode:

f = open("Newfie.txt","r")
f.close()

Read a file

f = open("Newfie.txt","r")
content = f.read()
print(content)
f.close()

Writing into a file

f = open("Newfie.txt","w")
f.write("Hello World!")
f.close()

 

Program to take excercise and food as input and then save it respective files. 

1) Write a funtion to select a user from the given list.

2) Select an option from exercise and food.

3) Select an option from write and retrieve.

import datetime

# users for the list
users=["Rohan","Harry","Pankaj"]

# Log dtls list
log_item=["Exercise","Food"]

# Function to log items from the list
def log_dtls(name):
    print("Select from the options: ")
    for i in range(len(log_item)):
        print(i," ",log_item[i])
    sel_dtls=int(input())
    print("You selected {}, {} \n".format(log_item[sel_dtls],name))
    return log_item[sel_dtls], name
            
# Functions to select the users from the list (users)
def select_user():
    print("Select from the options: ")
    for i in range(len(users)):
        print(i," ",users[i])
    sel_user=int(input())
    return log_dtls(users[sel_user])

# Funtions to save the details in the respective file
def enter_dtls(name,ch):
    if ch=="Exercise":
        f=open("Exercise.txt","a")
        ex = input("Enter exercise name:\n")
        time = datetime.datetime.now()
        f.write("\n"+name+" "+str([str(time)])+': '+ex)
        f.close()
    if ch=="Food":
        f=open("Food.txt","a")
        fd = input("Enter food name:\n")
        time = datetime.datetime.now()
        f.write("\n"+name+" "+str([str(time)])+': '+fd)
        f.close()
        
# Functions to retrieve respective files
def retrieve_dtls(name,ch):
    if ch=="Exercise":
        f=open("Exercise.txt","r")
        for line in f:
            if line.startswith(name):
                print(line,end="\n")
        f.close()
    if ch=="Food":
        f=open("Food.txt","r")
        for line in f:
            if line.startswith(name):
                print(line,end="\n")
        f.close()
        
if __name__ == "__main__": 
    cont='Y'
    while(cont=='Y'):
        k = select_user()
        print("\nSave or retrieve:\n1 to save\n2 to retireve: ")
        read_write = int(input())
        if read_write == 1:
            enter_dtls(k[1],k[0])
        else:
            retrieve_dtls(k[1],k[0])
        print("\nWant to continue: Y/N")
        cont = input()

 

 

 



Tags


Comments