Python scripting
Guided Practice 3.2 – Reading and Writing Files
Task 1 – File Paths
The most important part of reading and writing file is knowing where the file is in the system. We do this with what is called file paths. The file path is a string that represents the location of the file. It is broken into three major parts.
Using the example file: C:\documents\dogs\cats.txt
· File Path – The file location in the system where all folders are separated with either a forward or backwards slash. The drive letter of our example would be C: followed by the folders documents and the subfolder dogs.
· File name – The filename in our example would be cats
· File Extension – The file extension is added to the file to tell the system what type of document it is. In this case the document is a .txt file which tells the system it is a text file.
Let’s take another example:
D:\downloads\July\horoscope.doc
Split the file into the correct sections below:
File Path
File name
File Extension
What type of file is a .doc file?
Do the same for the two files below
C:\PythonFiles\names.txt
C:\Windows\System32\drivers\3ware.sys
File Path
File name
File Extension
You can also create a subfolder. Go to your C:\PythonFiles folder and do a right click on the open space in the folder. Go down until you see New > and then Folder in the create box.
This will create the new folder and highlight the name of the folder. Type the name
Change the file name to dist
Anything that goes into this folder will now have the file path of C:\PythonFiles\dist. Take a screenshot of your new folder.
Deliverables for Task 1
· Answer the questions about File path, file names, and extension.
· Take a screenshot of your created folder.
Task 2 – Pseudocode
Reading data from a file is a simple process of reading data until there is no more data in the file. This is done through the following simple process.
Pseudocode
· Open the file
· Read the first data item from the file
· Repeat until data item is blank
· Process the data from the file
· Read the next data item
· Loop
· Close the file
To write data into a file you loop through all of the data and write it to a file on the hard drive.
Pseudocode
· Process your data
· Open the file
· For each data item
· Write data to the file
· Close the file
Deliverables for Task 2
· Screenshot of the Pseudocode for your program
Task 3 – Program for Reading and writing files
Now you are going to write a program to read in a text file, process the data, and write out a sorted data to another file. This is a normal process for programs and is how they work in your system. The name of the file is names.txt and needs to be in your C:\PythonFiles folder. If the file does not exist there open your Canvas shell and download the file into the folder.
Now let’s create the Python program that will allow us to read in the file. The program will consist of three functions named readfile, writefile, and appendfile as well as the main program itself. Open you Python IDLE editor and create a new file called ReadNames.
First add your print with student ID to the top of your program.
print(“<Your StudentID>”)
Next we’ll create a function called readfile by typing. You will notice we have included the list names which will be passed back to the main program.
def readfile():
Next let’s create a variable with our File Path Name in it.
path = “C:\\PythonFiles\\names.txt”
Then let’s open the file based on these three items.
fopen = open(path, “r”)
In the program let’s add a loop to work through all items in the file. Then we’ll add a command to close the file so there is no more input from the file.
for line in fopen:
print(line)
fopen.close()
Now go to the bottom of the page and tab back to the left side and type
readlines()
Now run the program. You will see a very long list of names but it isn’t very useful. Let’s add the names into a list so we can manipulate them. At the top of your readfile program, after the path statement add an empty list
names = []
Then change your loop to the following
for line in fopen:
names.append(line)
fopen.close()
Add names to the function return parameters and to the readfile method as the last line of code
def readfile():
statements
return(names)
update your readfile method call to get the list from the readfile code.
names = readfile()
Run your program and take a screenshot of your output. Notice that you have a \n character (new line character) at the end of each name. Let’s add a command that will remove the \n from each name
line = line.replace(“\n”,””)
Run the program again to verify that the \n has been removed. Now let’s add a sort statement to the program that will sort the names alphabetically.
names.sort()
print(names)
Run your program again and take a screenshot of your sorted list.
Writing a file
Now we’re going to write out your sorted names list from your program to another file called sorted_names.txt. To do this first we’re going to program a second function named writefile
def writefile(names):
path = “c:\\PythonFiles\\sorted_names.txt”
fopen = open(path, “w”)
for line in names:
fopen.write(line)
fopen.close()
Run the program and then look at the sorted_names.txt file. You will notice that the file now has all of the names but they are smashed together on a single line. In order to fix this we need to add a newline character (\n) to the end of each name.
We are finally going to write a third function that will append information to the end of the file.
def writefile(line):
path = “c:\\PythonFiles\\sorted_names.txt”
fopen = open(path, “w”)
fopen.write(line)
fopen.close()
At the bottom of the program add the line
appendfile(“End of file”)
Run your program again and take a screenshot of the completed program and the outputted file sorted_names.txt.
Deliverables for Task 3
· Screenshot of your output with \n on each line
· Screenshot of your output with \n removed
· Screenshot of your completed program and sorted_names output.