ITEC-425 / SENG-425: Python Programming Lab Lab 6: Working With Files I/O
ITEC-425 / SENG-425: Python Programming Lab Lab 6: Working With Files I/O
In the following tasks, for the sake of conveniece, your Python code and the text files it is
referencing (reading or writing) should be in the same directory.
For the tasks in this lab, create and save a file called data.txt by copying and pasting
the following content. Save the file data.txt in the same folder/directory as your
Python code.
data.txt
Task 1
Write a program that reads a text file, and prints it line by line but in ALL CAPS.
In [1]:
# Open the file
fhandle = open("data.txt")
Task 2
Write a program that reads a file a text file, and counts the number of words in the file.
In [2]:
# Open the file
fhandle = open("data.txt")
Task 3
Write a program that counts the number of lines in a text file.
In [3]:
# Open the file
f = open('data.txt')
# To get the number of lines, find the length of the above list
print("The number of lines in the file: ", len(lines))
Task 4
Write a program that asks the user for a filename and a message. The program creates a
new file and saves the message in the file.
In [4]:
fname = input("Enter new file name: ")
msg = input("Enter your message: ")
f = open(fname, 'w')
f.write(msg)
f.close()
print("Your file has been created and your message is saved in the file.")
Task 5
Write a program that repeatedly asks the user for a to-do item, and appends it to a file
called todos.txt . When the user enters quit the program ends.
In [5]:
f = open('todos.txt', 'a')
while True:
todo = input("Enter your to-do item (or enter quit to stop): ")
Page 2 of 3
if todo.lower() == 'quit':
break
f.write(todo + '\n')
Enter your to-do item (or enter quit to stop): fix computer
Enter your to-do item (or enter quit to stop): complete assignment
Enter your to-do item (or enter quit to stop): buy tickets
Enter your to-do item (or enter quit to stop): pay bills
Enter your to-do item (or enter quit to stop): quit
All your todo items are saved in the file: todos.txt
Page 3 of 3