Learning about files, data, and iteration
In this section, we're going to take a look at how to handle files, data, and iteration with Python. This will give us information on how to use an algorithm to open, edit, and run already-existing Python files or new files. With iteration, we'll learn how to repeat lines of code based on some conditions, limiting how many times or under what conditions a section of the algorithm will run for. We'll start with files first.
Handling files in Python
In Python, the main function associated with files is the open()
function. If you are opening a file in the same directory, you can use the following command line:
fOpen = open('filename.txt')
If the file is in another location, you need to find the path for the file and include that in the command, as follows:
fOpen = open('C:/Documents/filename.txt')
There are a few more things we can tell the program to do in addition to opening the file. They...