Unit 11 Working with files Flashcards
8Activity: Open this file! (Windows)
Assume the following text file exists on a Windows computer, located at ‘C:\Users\aryan24\Documents\my_file.txt’. Note that the first line is a NAME, the second line is an AGE and the third line is a COLOR.
Julianne
11
blue
Reads in data stored in “my_file.txt” file.
Prints out the following lines, with the correct information filled in as it appears in the file. For example:
Hello, Julianne
You are 11
Your favorite color is blue
Open a text file on a Windows Machine
info = open(‘C:\Users\aryan24\Documents\my_file.txt’)
info_list = info.readlines()
info.close()
print(info_list)
print(“Hello, {}”.format(info_list[0]))
print(“You are {}”.format(info_list[1]))
print(“Your favourite color is {}”.format(info_list[2]))
How can you create a new text file to modify?
To do that, we use a second parameter for the open function. This parameter tells Python that we want to write a file instead of just read to it. We use a ‘w’ for write to tell it that
Can the open() function only create a file object?
No. The open() function can be use to do a lot of different things other than just read in what’s in a file
When we’re finished writing to a file, we have to tell Python that by using the ___________
close() function
Let’s say you want to add the first line of your joke to a new file. How should you do this?
How do you add to a file?
To do this, we use the write() function that works on our file object.
new_file = open(‘C:\Users\aryan24\newfile.txt’,’w’)
new_file.write(“What’s a pirate’s favourite letter?”)
new_file.close()
You need to use a different letter for the second parameter when we open it. Otherwise, Python will start a new file and erase our old one.
The letter we want to use is “a” for “append” (which means to add on to something )
new_file = open(‘C:\Users\aryan24\newfile.txt’,’a’)
new_file.write(“\n”)
new_file.write(“Arrrr!”)
new_file.close()
You can see that we included a line to add that special slash “\n” to tell our text document that we wanted to start a new line. That let it format our joke appropriately. this means that now the newly added line of code will be added on to the new_file.txt
Write this data to a file so that your earned money is always stored even after closing the program for the task below. Keep track of all the money you are earning. Now that we have learnt how to use files, we can write a program that can calculate and keep running total of the money you are earning.
Read initial earnings from file
earnings_file = open(‘C:\Users\ryan_\Desktop\earnings.txt’)
earnings = int(earnings_file.read())
earnings_file.close()
def print_menu():
print(“You have currently earned: ${}”.format(earnings))
print()
print(“1- Add new earnings”)
print(“2- Quit program”)
print()
choice = int(input(“Please make a selection from the menu:”))
return choice
print(“Welcome to the Summer Earnings Calculator…”)
user_choice = print_menu()
new_funds = 0
while user_choice == 1:
new_funds = int(input(“Enter earnings to be added: “))
earnings = earnings + new_funds
user_choice = print_menu()
print(“Thank you for using the Summer Earnings calculator!”)
earnings_file = open(‘C:\Users\ryan_\Desktop\earnings.txt’,’w’)
earnings_file.write(str(earnings))
earnings_file.close()
The first line opens up the file for reading and then we read in the current earnings from the file. We have to remember to change it into an integer because it is a number. Lastly, we need to close the file when we are all done with reading.
Next, let us define a function called print_menu() that will display the current earnings and then print the program’s options and get the input.
We will need to create a variable new_funds, to keep track of how much money should add to our running total of Summer earnings.
We are going to add a while loop in the main program that will continue to run until Quit is selected. Each time new funds are entered, we will add that amount to the current earnings and print out the menu again.
The last thing we need to do in our program is write that new total of Summer earnings to our file, but how do we do that?
First, let’s open our file with the ‘w’ parameter because we want to overwrite the number that was in it before.
In this case, we don’t want to add a new number to the end with the append option.
We can’t use the file that we created before because we only opened it for reading not writing.
You will note that we have to convert our earnings to a string because that is what is required to write to a file.
The final step is to close the file so that Python knows we are ready for the file to be saved.
What is the advantage of using files?
Using files allows us to accurately save information between different runs of our program.
When you want to add something to a file, how do you code it?
You delete your previous code and then add in a second parameter (the first parameter being the notepad file name) and the second one being ‘a’ with the parameters separated by a comma. So when you click on your notepad again, the code will be added to your previous code on your notepad
What does the filename.write(“\n”) does?
It adds a new line in the notepad.
What is the description for each of the open() command below?
new_file = open(‘C:\Users\aryan24\newfile.txt’,’r’)
new_file = open(‘C\Users\aryan24\newfile.txt’,’w’)
new_file = open(‘C\Users\aryan24\newfile.txt’,’a’)
The description for the first open() command is open a file for reading.
The description for the second open() command is opening a file for writing
The description for the third open() command is open a file for appending.
What should the code be for the activity below?
Activity: Update that file!
Open up a new file in IDLE and write a Python program. Using the text file that you created in Activity 11.1, complete the following tasks:
Your program should read the data from the “Students.txt” file.
It should then display the names in the following format:
Student Name
—————–
John Doe
Michael Smith Annie Warner Ask the user whether they want to enter a new student name. If the user enters "no", then end the program. If the user enters " yes", then get the new name and add that into the "Students.txt" file. Repeat task #3 above until the user enters "no." Finally, run your program again and see whether the new student names are printed from the "Students.txt" file. For example, if the user entered a new name “Shelly Ryan,” the program should display an updated list as shown below: Student Name ----------------- John Doe Michael Smith Annie Warner Shelly Ryan
Function to write names into the text file
Here is the code suggested by cty:
#Function to read from the text file
def read_data():
my_file = open(“Students.txt”)
student_name = my_file.readlines()
data_count = len(student_name)
print(“Student Name\n”)
print(14 * “-“)
for count in range(0, data_count):
print(student_name[count])
my_file.close()
def write_data():
my_file = open(“Students.txt”, “a”)
my_file.write(name + “\n”)
my_file.close()
read_data()
more_names = True
while more_names:
response = input(“Do you want to add any new names? (y/n) “).lower()
if response == ‘y’:
name = input("Student name: ") write_data()
else:
more_names = False
Here is my code:
#Function to enter a new student name.
def choice():
choice = input(“Do you want to enter a new student name? (yes or no)”)
return choice
while True:
#Call the function
user_choice = choice()
if user_choice == “yes”:
new_name = input(“Enter new name:”)
Students = open(‘Students.txt’,’a’)
Students.write(‘\n’)
Students.write(new_name)
Students.close()
print(f”{new_name} has been added.”)
elif user_choice == “no”:
break
else:
print(“Invalid input. Please enter ‘yes’ or ‘no’.”)
An absolute path will always start with ______________
An absolute path will always start with a “C:\” on Windows or a “/” (forward slash) on a Mac.
NOTE: Since an absolute file path refers to a specific username and path only on your computer’s filesystem, you’ll need to ________________________
NOTE: Since an absolute file path refers to a specific username and path only on your computer’s filesystem, you’ll need to update it if you want to send your program to someone else.
Windows
my_file = open(‘C:\Users\USERNAME\Documents\myfile.txt’)
Mac
my_file = open(‘/Users/USERNAME/myfile.txt’).
This way of referring to a file is called an _______________________.
Windows
my_file = open(‘C:\Users\USERNAME\Documents\myfile.txt’)
Mac
my_file = open(‘/Users/USERNAME/myfile.txt’).
This way of referring to a file is called an absolute path.
When you use a relative path _________________________________.
When you use a relative path, you have to think about where you saved your Python .py file on your computer and then where you saved the file you want to access.
What is the easiest way to handle relative path?
The easiest way to handle this is to save the file that you want to access in the same folder as your .py program file, like this:
Here, both the text file (called “my_file.txt”) and the Python script (called “my_python_script.py”) are saved on the Desktop. Since they are in the same folder, you can simply open the file using the file name, like this:
my_file = open(‘my_file.txt’)