2.2 Basic File Handling Flashcards
Text Files and Python
In python, like all other languages, it is possible to store in text files data held within the program (such as data in variables and lists).
This is great as is means that when our program closes, we can still keep our data.
Creating the file and opening it in write mode
Before we can write data into a text file we first need to create the text file.
We need to use a new function, called ‘open()’. This creates the file and allows us to write text to it.
Firstly, we create a variable that python will use to identify the text file, then we use the open function to assign the external file to it.
newfile = open(“The New text File .txt”,w)
“w” means we will be writing on the file after opened
Writing to the file
To start writing to the file we have created we need to add ‘.write’ to the end of our new variable followed by brackets.
newfile.write(“Hello world”)
If we are going to write more than one line to the file, we need to tell the computer when to start a new line. To do this, we use ‘\n’ at the end of each line.
newfile.write(“Hello world/n”)
Closing the File
We need to close the file after we have written to it otherwise we will not be able to see it once we are finished.
All we have to do to close the file is add ‘.close’ to the end of our variable.
newfile.close()
The Result
The file that is created and written to will be in the same folder as the program that you made to create the text file.
Opening a file in read mode
We first need to open the file we are using in read mode. To be able to read a file you need to have created one beforehand.
We do this by typing in the file name and file type, followed by a comma and “r”. This tells the computer that we will be opening the file in order to read its contents.
newfile = open(“TheNewFile.txt,”r”)
Reading the File
All we have to do to actually see the text within the file is print the text file’s variable with .read() attached to the end of the variable name.
print(newfile.read))
Reading one line at a time
To read only one line at a time we use ‘.readline()’ instead of .read()
print(newfile.readline()))
Reading Only Specific Lines
To read specific lines we use ‘.readlines()’ followed by the line number in square brackets.
print(newfile.readlines()[2])