At the end of this lesson, you will be able to:
be able to read and write to files
review string manipulation
Almost all programs store some information on a hard drive or a local storage system of some kind. Users routinely expect that information (data) that is inputted in a program to available in later sessions. The ability to use long term storage is a key feature of modern programs. In terms of programming this requires two steps:
store the data into a file.
retrieve, load or input the data from the file into a program.
We will be looking at both aspects of this task in this activity.
Storing Data
Python 3 uses an object based approach to file input and output. To create a file you must first open a file using the following syntax:
filehandle = open("filename.txt", 'w')
The filehandle is the variable that is used to access/reference all the functions related to managing that file. The function open is used to create the file. Files that are created for writing will be empty to begin. If there is a file with the same name, then that file will be deleted when the command is used!
The first parameter to the function is "filename.txt", which is a string for the filename on the disk/storage device. It is good idea to use the .txt ending (also called an extension) to identify the file as a standard text file that can be read by programs such as notepad. The second parameter in the open function "w"makes Python open the file so that it can store or write information.
Once the file handle, filehandle, is created, the file is open for writing. Writing to file involves using the command
filehandle.write("text to write")
You may use the write command as many times as necessary. The file must be closed to make it usable. The command to close the file is
filehandle.close()
Below is an example of a program that uses these commands
It is important to notice the use of the dot command structure - the filehandle.write() and filehandle.close() type of commands. This structure means that the write() and close() are connected to the file handle created in the open function. If you created a second file, you could use those commands, but they would relate only to that new filehandle.
You can use the write command to write as many times as you would like.
Notice that the above program converts the integer i to a string and adds a new line to the line of text being written to the file. The write command will only accept text (i.e. strings or characters) and does not start a new line on its own. You must convert numbers to strings and put the end code (usually a new line) yourself.
So where is the file that you created? Using the configuration we are currently using, the file will be saved in the same directory as your python code. To view the file contents you can open the file in Notepad by 'exploring' to the workspace directory under your user space, or refreshing the pydev Project Explorer.
Retrieving Data
Opening a file to read is similar to opening a file to write. The command is
fileHandle = open ("filename.txt", 'r')
There are three ways of handling the reading in of the data from a file in Python. It is important to select the method that is most appropriate for the circumstance.
fileHandle.read() The command will read and input the whole file all at once.
fileHandle.read(numberOfCharacters) The command will read the number of characters specified as the parameter (the number inside the brackets).
fileHandle.readline() The command will read one line of the file at a time.
Regardless of the method used, at the end of the process you must close the file using the command
filehandle.close()
Method #1: Reading the entire file
It is possible to read in all of text file in one command. Using a string variable, contents, the command to input the whole file into the variable is
contents = fileHandle.read()
The following program is an example of this method of reading a file.
Method #2: Reading a number of characters
Python permits the reading of a specific number of characters at a time. This is done by using the command
content = fileHandle.read(num)
where num is an integer. This command can be used to read a single character at a time, or a file in which the text is formatted into fixed length fields.
Method #3: Reading one line at a time
Reading files line by line is done by using the command
line = fileHandle.readline()
This command needs to be used to read each line of a file. An example of this usage follows.
There are other ways to use Python to read and write files, however these are the most straightforward. You may wish to consider using files in your final project (RST)
Start by accepting this GitHub Classroom Assignment to house your code for these tasks.
Create a program that will accept a multiple choice question, four answers, and the letter of correct answer. This will be six lines, and then store the questions in the file questions.txt. Name your program Q1Questions.py
Create a second program that will read the file questions.txt, formatted as described above, and pose the questions to the user. The program will keep score of the number of questions answered correctly. Name this program Q2Quiz.py
work on weekly assignment