This lesson covers reading and writing to files. However, we would first review reading from keyboard and writing to the screen.
We would cover the following:
- Writing to Screen Reading from Keyboard
- The input and raw_input Functions
- Creating a File
- The open method
- Attributes of a File Object
- The close() method
- Reading From File
- Writing to File
1. Writing to Screen Reading from Keyboard
You already know how to write to the screen. You use the print function and specify the text to be written as parameter. For example
print("Hello World") name = "Kindson" print("My name is" + name)
You can run the code above to see the output. I also recommend you review how to us the printf() function under Python Strings.
Now, you you can also read input from the keyboard using
- input Function
- raw_input Statement
2. The input() and raw_input() Functions
Both functions are used to read user input from the keyboard.
The raw_input() reads a single line of input form the keyboard and returns it as a string. (not available in Python 3)
The input() function also reads on line from the keyboard. However it assumes that the input is a valid Python expression. So it evaluates it and returns it.
Examples are given below
name = input("Please enter your name: ") print("You entered " + name)
3. Creating a File
Now we we would discuss how to read and write from files. To be able to to that, you will be using the file object. The file object provide the functions you need to read and write to files in Python. One of such functions if the open() function.
4. The open() Function
Before you can read or write to file, you must first open the file using the open() function. The open() function returns a file object. Therefore you must assign it to a file variable. For example
myfile = open("C:/test.txt", "r")
The above code creates a file object myfile. Then what is returned from the open() function is assigned to it. The second parameter “r” is the file mode. It indicates the the file is open for read-only. There are other file modes as well as listed in the table below
Sr.No. | File Modes and brief description |
---|---|
1 | r Opens a file for reading only and places the pointer in the beginning of the file. This is the default file mode. |
2 | rb Opens a file for reading only but in binary format. This is the default mode. |
3 | r+ Opens a file for both read and write. |
4 | rb+ Opens a file for both read and write in binary format. |
5 | w Opens a file for writing only. It however overwrites the file if the file exists. But it the file does not exist, it creates a new file for writing. |
6 | wb Opens a file for writing only in binary format. It however overwrites the file if the file exists. But it the file does not exist, it creates a new file for writing. |
7 | w+ Opens a file for both writing and reading. It however overwrites the file if the file with same name exists. But it the file does not exist, it creates a new file for writing. |
8 | wb+ Opens a file for both writing and reading in binary format. It however overwrites the file if the file with same name exists. But it the file does not exist, it creates a new file for writing. |
9 | a Opens a file for append. The file pointer is placed at the end of the file if the file with same name exists. So whatever is written is appended to the end of the file. But it the file does not exist, it creates a new file for writing. |
10 | ab Opens a file for appending in binary format. The file pointer is placed at the end of the file if the file with same name exists. So whatever is written is appended to the end of the file. But it the file does not exist, it creates a new file for writing. |
11 | a+ Opens a file for both appending and reading. The file pointer is placed at the end of the file if the file with same name exists. So whatever is written is appended to the end of the file. But it the file does not exist, it creates a new file for writing. |
12 | ab+ Opens a file for both appending and reading in binary format. The file pointer is placed at the end of the file if the file with same name exists. So whatever is written is appended to the end of the file. But it the file does not exist, it creates a new file for both reading and writing. |
5. Attributes of the file Object
So if you have opened a file, what can you do with it? Now, the file object provides a number of attributes that give you information about the file. These attributes are tabulated below
SN | Attribute and brief description |
---|---|
1 | file.closed Checks if the file is closed. Returns true if the file is closes. Returns false if otherwise |
2 | file.mode Returns file access mode with which file was opened with |
3 | file.name Returns name of the file on disk. |
The code below illustrates how to open a file and get information about the file.
# open a file called Tutorial.txt myfile = open("D:/data/Tutorial.txt", "rb") print("Name of file: " + myfile.name) print("Is it closed: " + str(myfile.closed)) print("The file mode: " + myfile.mode)
If you run the code , then you will have the output give below:
Name of file: D:/data/Tutorial.txt Is it closed: False The file mode: rb
6. The close() Method
Just as you can guess by now, if you open a file, you should be able to close it. You can do this using the close() method. However, in addition to closing the file, the close() method also flushes any unwritten information before closing the file. It’s good to close a file after using it by explicitly calling the close() method. However, if you forget to close a file, Python would automatically close it if it goes out of scope.
7. Reading the Content of File
No that you have opened a file, the next thing to do is to read the content of the file. Probably display the content to the output.
First, you need to open the file in read mode. Then you call the read(n) method of the file object. The read method takes an optional parameter which is the number of characters to read from the file. If n is not specified, then the entire file is read.
For example, the file Tutorial.txt contains list of names. The program below opens the file and reads the content of the file, then prints it out to the output.
# open a file called Tutorial.txt myfile = open("D:/data/Tutorial.txt", "r") name = myfile.read() print(name) myfile.close()
The above code reads the content of the file and assigns it to a variable name. So name would now hold all the content of the file. So when we call print(name), the entire content of the file is printed out a shown below
Kindson Munonye Jackie Ugwueke Solace Okeke Saffron Imolode
The table below gives a summary of all the methods you can use to read data from a file.
SN | Method and decription |
---|---|
1 | read() Read the entire content of a file |
2 | read(n) Reads only n characters from a file |
3 | readline() Reads a line of text from the file |
4 | readlines() Reads all the content of a file into a list line by line |
8. Writing to File
In addition to reading content of a file, you can also write data into a file. To do that we use the write method. You use the write method to write a string into a file. However, the line method does not add a newline character to the end of the file.
The code below open a file in write mode. Then it writes three items into the file.
# open a file called Tutorial2.txt for writing myfile = open("D:/data/Tutorial2.txt", "w") myfile.write("Python Programming Tutorials \n") myfile.write("Coding Challenge \n") myfile.write("Java Programming Tutorial") myfile.close()
If you execute this code it creates a file named Tutorials2.txt in the location D:/data and writes the the specified strings into the file.