7) a. Reading and Writing Files Examples




There is a lavish club that has openned in your vicinity named Midnight Rocks. You had booked it for the weekend and were really looking forward to going there but your friends have ditched you at the last moment. Now you will have to go there alone. For stag entries, there is a password that everyone has to say to the bouncer before entering the premises. You have the access to their system file which contains the password. There is only a single line in the file which is the password. Please read the file, password.txt, and print it on the console. Let us assume the file is in E: drive.

1
2
3
4
Program:
#password_fetcher.py
with open('E://password.txt') as password:
    print(password.read())




Your professor is creating a database of students with their name and emailIDs separated by colon. He is entering each name/emailID on an new line and is doing this task since morning. He has a lot of students to go through and comes up with an idea. He wants each student to update their respective name and doesn’t want to do this by himself. You want to try something new and instead of opening a file in some text editor want to write a script that will open the file and enter your name and emailID separated by colon at the end of the file. The file is saved in E: drive as students_db.txt. Make sure to add a new line character at the end.

1
2
3
4
5
6
Program:
#append_name.py
name = 'noname'
email = '[email protected]'
with open('E://students_db.txt', 'a') as file:
    file.write('{}:{}\n'.format(name, email))




Jane works for an established publishing business and handles the finances for them. She has a list of things bought by the firm and it is present in a file items.txt in E: drive. She wants to go over them and add the numbers one by one. You happen to visit her one day while she was doing this and have a better way of handling this. All the rows of the file are formatted in :. You want to write a python script for her that iterate over the file, add all the amounts and print the final answer onto the screen. Please write the script to help her in this situation.

1
2
3
4
5
6
7
8
Program:
#add_amounts.py
total = 0
with open('E://items.txt') as file:
    for line in file.readlines():
        amount = int(line.split(':')[1])
        total = total + amount
print('The total is, ', total)




Magician Roka is a planning to visit your city this weekend and he is considering a group of volunteers from your city. You have never heard of him and is not a fan of magic shows so do not want to volunteer for this but your friend writes your name on a list and gives it to Roka as a prank. You get to know about him and wants him to give a taste of his own medicine. You have the magician’s system with you and want to write a script that will replace your name, Tuna, to your friend’s name Kama and write this into a new file volunteers_new.txt. All the names are separated by new line character in this file. The original file is saved as volunteers.txt in E:.

1
2
3
4
5
6
7
8
9
Program:
#replace_name.py
with open('E://volunteers.txt', 'r') as volunteer_file:
    with open('E://volunteers_new.txt', 'w') as volunteer_file_new:
        for name in volunteer_file.readlines():
            if name == 'Tuna\n':
                volunteer_file_new.write('Kama\n')
            else:
                volunteer_file_new.write(name)




Today is 1st January and your friend, Bane, has created a resolution list. He has saved the file as resolutions.txt in E: drive. He wants this file to be updated in future also. You, being the python expert, lends him a helping hand and writes a script that gets the input from user and then appends it to the file. Also everytime this is done, the code also prints all the contents of the file. Please write this s cript for your best friend Bane.

1
2
3
4
5
6
7
8
9
Program:
#resolutions.py
print('Enter the new resolution')
resolution = input()
with open('E://resolutions.txt', 'r+') as resolutions_file:
    for line in resolutions_file.readlines():
        print(line)
    # adding the resolution
    resolutions_file.write(resolution + '\n')




You are a traffic policeman whose duty is to issue ticket to people who have violated traffic rules. In doing so, you update the licence number in a software which creates a file .txt. You don’t want to issue tickets to these offenders again in the same day. Everyday the system is rebooted and all the data of previously issued ticket is lost. As you are also interested in python you try to write the code for handling same. The software should get the licence# as an input and then create a file licence#.txt and with file contents of licence# itself. The file should be saved in E:

1
2
3
4
5
6
7
Program:
#licence_ticket.py

print('Enter the licence number')
licence = input()
with open('E://' + licence+'.txt', 'x') as licence_file:
    licence_file.write(licence)




A pschotic serial killer has entered your city and is creating havoc. The only way to survive is to be safe and hide yourself from getting kidnapped till the police gets a hold of him. He has a database of names saved in his E: directory under file named names.txt. These are the names which he kidnaps. You have gotten hold of this file and want to write a script in which people can enter their name and figure out if their name is present or not. Each name is separated by a comma. Write a linear search script that searches through the names and alerts if the name is present..

1
2
3
4
5
6
7
8
9
10
11
Program:
#serial_killer_file_traversal.py

print('Enter your name')
input_name = input()
with open('E://names.txt', 'r') as killer_file:
    names =killer_file.readline().split(',')
    for name in names:
        if name == input_name:
            print('Your name is there in the list. Please hide')
            break