Unit 11 Working with files Flashcards

1
Q

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

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you create a new text file to modify?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Can the open() function only create a file object?

A

No. The open() function can be use to do a lot of different things other than just read in what’s in a file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

When we’re finished writing to a file, we have to tell Python that by using the ___________

A

close() function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the advantage of using files?

A

Using files allows us to accurately save information between different runs of our program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

When you want to add something to a file, how do you code it?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the filename.write(“\n”) does?

A

It adds a new line in the notepad.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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’)

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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
A

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’.”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

An absolute path will always start with ______________

A

An absolute path will always start with a “C:\” on Windows or a “/” (forward slash) on a Mac.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

NOTE: Since an absolute file path refers to a specific username and path only on your computer’s filesystem, you’ll need to ________________________

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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 _______________________.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

When you use a relative path _________________________________.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the easiest way to handle relative path?

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Is the code the same for either a Windows or a Mac computer for relative path?

A

Note that the code is the same for either a Windows or a Mac computer. Using a relative path like this doesn’t depend on the way your computer’s operating system interprets the file structure. We can represent this file structure like this, showing that they are both in the same folder:

diagram of file structure organization showing that my_file.txt and my_python_script.py is a subset of computer’s desktop

computer’s desktop
|
——————————
| |
my file.txt my_python_script.py

18
Q

If you want to be able to share your code with your friends, ______ path is the easiest way to structure and design your programs.

A

relative. When you turn in your assignment for this unit, you are free to use either absolute or relative path to refer to your file.

19
Q

As you become a more skilled programmer, your Python scripts might have several files that they reference. In order to better organize them, you may want to put them in a ________ just for files.

A

As you become a more skilled programmer, your Python scripts might have several files that they reference. In order to better organize them, you may want to put them in a folder just for files.

We can represent this file structure, including the separate “files” folder as shown below:
Computer’s desktop
|
________________________________________________
| |
files my_python_script.py
|
|
____ my_file.txt

20
Q

To reference anything inside the “files” folder, include a ________________________. On windows, you need to use a _________ and on a Mac you need to use a _______________.

A

To reference anything inside the “files” folder, include a slash between the name of the folder and the name of the file. On Windows you need to use a “" (backslash) and on a Mac you need to use a “/” (forward slash).

Windows
my_file = open(‘files\myfile.txt’)
Mac
my_file = open(‘files/myfile.txt’)

It’s very important that you don’t put a slash before the folder name, as that means something different to the computer (that’s saying that you want to use an absolute path). You only put a single slash after or between any other folder names – you can have any number of folders as shown beloe:

Computer’s desktop
|
__________________
| |
files my_python_script.py
|
input_files
|
my_file.txt

The code to access the “my_file.txt” file would then look like this:

Windows
my_file = open(‘files\input_files\myfile.txt’)
Mac
my_file = open(‘files/input_files/myfile.txt’)

21
Q

What would the code be to accessing the “my_file.txt”?
Computer’s desktop
|
__________________
files my_python_script.py
|
input_files
|
my_file.txt

|

A

Windows
my_file = open(‘files\input_files\myfile.txt’)
Mac
my_file = open(‘files/input_files/myfile.txt’)

22
Q

What happens if the code file is in a different folder than the folder that contains your files?

We can represent this file structure, including the two separate folders “files” and “code” as shown below:
Computer’s desktop
|
________________________________________________
| |
files code
| |
my_file.txt my_python_script.py

A

In Python, you use two periods without a space between them (..) to indicate “go up one folder level” when you are using relative file paths. In this example, you would want to “go up one level” from where “my_python_script.py” is stored, then go to the “files” folder, and then to the “my_file.txt” file. The Python code looks like this:

Windows
my_file = open(‘..\files\myfile.txt’)
Mac:
my_file = open(‘../files/myfile.txt’)

23
Q

What should the code be to correctly opens “file2.txt” for reading in Python on Windows?

                       Computer's Desktop
                                        | \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
     |                                                        | files                                                     code |                                                           | |-- file1.txt                                        |-- script1.py |--- file2.txt                                    |-- script2.py
A

my_file = open(‘..\files\file2.txt’)
Response:
Use “..” in the file name to first go up one directory and then down into the “files” folder.

24
Q

What is wrong with this code?
File not found
The most common error we get is when we try to open a file and the file is not found. It may be that the file is not present in the specified file path or that the file name is incorrect. Let’s consider the code below:

my_file = open(‘C:\Users\USERNAME\myfile.txt’)
When we run this code, if ‘myfile.txt’ does not exist or if the file path is wrong, Python will throw a FileNotFound error:

Traceback (most recent call last):
File “C:\Users\96C32572223744\Desktop\test.py”, line 2, in <module>
my_file = open('C:\\Users\\USERNAME\\myfile.txt')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\USERNAME\\myfile.txt'</module>

A

*TIP: To fix this type of error, make sure that the file path is correct and the file exists with the exact name given in the full path.

The same thing applies if you are using a relative path. Remember that a relative path is used when we save the text file in the same folder that we saved our program file. Then we can simply refer to the file name as shown below:

my_file = open(‘myfile.txt’)

25
Q

If Python is unable to find any file with the name ‘myfile.txt’ in the current working directory, it will again throw a _______________

How do you fix this error?

A

FileNotFoundError

FileNotFoundError: [Errno 2] No such file or directory: ‘myfile.txt’

To fix this error, make sure that you are referring to the correct file and that the file exists in the same directory as the Python script.

*TIP: As a beginning programmer, it is a good idea to keep all text files in the same folder where you have your Python script file and use relative paths in your code.

26
Q

What is the io Error?

A

This error occurs when you are trying to write to a file without specifying the proper access mode when working with files.

27
Q

io Error
What does io error mean?

Another fairly common mistake when working with files is trying to write to a file without specifying the proper access mode. Let’s consider the example below:

file=open(‘myfile.txt’)
file.write(“hello”)
file.close()
Running this program will throw the following error:

Traceback (most recent call last):
File “C:\Users\96C32572223744\Desktop\test.py”, line 2, in <module>
file.write("hello")
io.UnsupportedOperation: not writable</module>

Why did this error occur?

A

io stands for Input/output.

This error occurred because we forgot to include the second argument in the open() function which specifies the mode in which to open the file. Python by default opens the file in the read only mode. If we want to open a file in write mode, we must specify the second argument that allows for writing, for example:

file=open(‘myfile.txt’, ‘w’)
file.write(‘hello’)
file.close()

28
Q

Similarly, we will get an error if we try to read from a file that is opened in write only mode. Have a look at the following code:

file=open(‘myfile.txt’, ‘w’)
text=file.read()
print(text)
When we run this code, we get the following error:

Traceback (most recent call last):

File “C:\Users\96C32572223744\Desktop\test.py”, line 2, in <module>
text=file.read()
io.UnsupportedOperation: not readable</module>

Why did this error occur and how can we rectify it?

A

In the above code, the file ‘myfile.txt’ is opened in the write only mode and so it cannot be read from. If you want to read data from the file, make sure to use the correct mode in the open() function that allows you to read.

*TIP: It is a good practice to always close the file using close() method. Closing the file ensures that the program does not crash and frees the file for other use.

29
Q

Errors with file format
Finally, we need to know how the data is written in the file to make sure we read that data correctly. When writing into the file we must write the data in the correct format so that the data can be correctly retrieved by someone else at a later time.

For example, let’s say that our program is reading and writing student records to and from a file. Each student record has 3 fields or columns – name, address, and grade level. To read the student records correctly, we will save each record in a _________________
Also, we need to use a _________ or ________ between each column.
Will a simple ‘space’ work as a delimiter?
How about a comma?

What should the code be?

A

Errors with file format
Finally, we need to know how the data is written in the file to make sure we read that data correctly. When writing into the file we must write the data in the correct format so that the data can be correctly retrieved by someone else at a later time.

For example, let’s say that our program is reading and writing student records to and from a file. Each student record has 3 fields or columns – name, address, and grade level. To read the student records correctly, we will save each record in a separate line. Also, we need to use a delimiter or separator between each column. Note that a simple ‘space’ will not work as a delimiter because the name and address fields both have spaces in them. Similarly, a comma is not a good candidate for delimiter because the address field uses commas to separate street, city and state. For this data file, a semi colon (“;”) would be an ideal delimiter because we aren’t using a semi colon anywhere in our student records. Here is an example of a good format for the data in our file:

John Doe;123 Test Street, Vienna, VA 22345;8
Mike Smith;33 Main St, Columbus, OH 33221;10
Judy Milligan;5 Davis Drive, Baltimore, MD 32234;12
Now, we shouldn’t have a problem writing correctly into the file:

my_file.write( name + “;” + address + “;” + grade_level + “\n”)
Reading from this file wouldn’t be hard either:

my_file = open(“datafile.txt”)
my_record = my_file.readlines()
for count in range(0, len(my_record)):
column = my_record[count].split(“;”)
print(column[0] + “\n” + column[1] + “\n” + column[2])
my_file.close()
This code should output:

John Doe
123 Test Street, Vienna, VA 22345
8
Mike Smith
33 Main St, Columbus, OH 33221
10
Judy Milligan
5 Davis Drive, Baltimore, MD 32234
12
What is happening in this code? First, we read the file contents as a list of separate lines. Then, for each line (or record), we call the split() function with the “;” delimiter to access each field in the record. At this point, we have access to all of the data from the file and can complete any tasks we need to. If we had used a comma (“,”) or space as a delimiter, we would have problems parsing out the data from the file and our program would have gotten more complex. As a program increases in complexity, the chance for errors and bugs increases as well.

30
Q

Ultimately, what are six things you need to remember when working with files?

A

Summary
Remember to give the correct path with correct filename, otherwise you will get an error.
Make sure the file already exists before reading from it.
Use the correct second argument in the open() function to specify which mode the file is to be opened.
Remember to always close files when you are done using them in your program.
Identify the correct format or layout of the data. Then, read and/or write content to the file accordingly.

31
Q

What will “datafile.txt” contain after the user runs the program three times to enter the following student records?

Code:

 my_file = open("datafile.txt","w")
 student_name = input("Enter student name: ")
 course_name = input("Enter course name: ")
 course_grade = input("Enter grade : ")
 my_file.write(student_name + "," + course_name + "," + course_grade)
 my_file.close() Data Entered:

Name    Course  Grade
=====================
James   Python  98
Mike    Java    88
Patty   Scratch 93 Question 1Select one:

a.
James,Python,98,Mike,Java,88,Patty,Scratch,93

b.
James,Python,98
Mike,Java,88
Patty,Scratch,93

c.
Patty,Scratch,93

d.
An error message will be displayed and the program will not run.

A

c
.write will overwrite the file

32
Q

Which File object method would you use to read the entire contents of a file as a list?

Question 2Select one:

a.
read()

b.
readline()

c.
write()

d.
readlines()

A

d

33
Q

What is the output of the following program?

“datafile.txt” File:

Apple
Orange
Banana Code:

my_file = open("datafile.txt")
my_content = my_file.readline()
print(my_content)
my_file.close() Question 3Select one:

a.
Apple

b.
Apple
Orange
Banana

c.
[‘Apple\n’, ‘Orange\n’, ‘Banana\n’]

d.
It will display an error message.

A

a

34
Q

Which File object method would you use to read the entire contents of a file as a string?

Question 4Select one:

a.
read()

b.
readline()

c.
readlines()

d.
write()

A

a

35
Q

Which of the following statements will allow us to write information to a file that already exists?

Question 5Select one:

a.
datafile = open(“addtome.txt”)

b.
datafile = open(“addtome.txt”, “w”)

c.
datafile = open(“addtome.txt”, “a”)

d.
all of the above

A

c

36
Q

Which of the following starts a new line in a file?

Question 6Select one:

a.
\n

b.
\e

c.
\newline

d.
\cr

A

a

37
Q

An absolute path will always start with which of the following on a Windows computer?

Question 7Answer

a.
C:\

b.
C:

c.
WINDOWS:

d.
WINDOWS:\

A

a

38
Q

Assume there is NO file called datafile.txt in the folder where you have saved the following code snippet. What will happen if you run the following code snippet?

my_file = open("datafile.txt")
my_file.write("My text")
my_file.close() Question 8Select one:

a.
It will display an error message saying “No such file or directory: ‘datafile.txt’”.

b.
The program will run without any error but the data will not be written in the file.

c.
The program will run successfully by writing the text in a file named datafile.txt.

d.
The program will display an error other than one having to do with the file.

A

a
Explanation:
By default, open() is in read mode (“r”). If the file does not exist, Python raises a FileNotFoundError.
Since the file is not opened in write mode, the program will fail before reaching the write() call.
Correct Answer: a. It will display an error message saying “No such file or directory: ‘datafile.txt’.”

39
Q

Consider the following program. Assume there is no file called “datafile.txt” is in the folder where you saved and ran this program. What will be saved inside “datafile.txt”?

my_file = open("datafile.txt","w")
book_list = ["Harry Potter", "Magic Tree House", "The Rainbow Fish"]
for count in range(0, len(book_list)):
    my_file.write(book_list[count] + "\n")
my_file.close() Question 9Select one:

a.
There will be nothing in the file after the program is run.

b.
It will display an error message.

c.
Harry Potter
Magic Tree House
The Rainbow Fish

d.
Harry Potter\nMagic Tree House\nThe Rainbow Fish

A

c

40
Q

An absolute path will always start with which of the following on a Mac computer?

Question 10Answer

a.
/

b.
//

c.
/macOS

d.
//macOS

A

a