Some of the I/O operations require us to install certain library. The following is working examples using Jupyter notebook, so it works for Jupyter notebook only. I do not install Jupyter notebook, so I used the browser version from the Jupyter’s website to continue learning.
Create a file at Jupyter notebook
Start the syntax with,
See below for an example code I did,
Once, I hit the “Run” button, it showed the “Writing myfile.txt”. The file is successfully written. My questions are:
1. Where did the file save since I was using the online browser version?
2. Why is it using the symbols, “%%“? Is it just for Jupyter Notebook?
Is there anyone can give me an advice?
Reading a file
How to access a file?
myfile.txt was created and able to be accessed when I used the following codes,
myfile = open(‘myfile.txt‘)
Yes, correct the syntax is open(‘<filename.extension>‘)
I will know if my file is able to be accessed or failed, if I did not have the file or typed a wrong filename or it has a wrong file location path, an error will throw on the screen. See the example below:
The myfile = open(‘myfile.txt‘) does not return the content of the file. It returns something called file object. It then allows us to read the file. In open() method, there are various modes can be used. Example of modes,
- mode =’r’ is read only
- mode =’w’ is write only
- mode =’r+’ is read and write
- mode =’a’ is append only. Add something at the end of the file.
- mode =’w+’ is write and read. Overwrite the existing file.
Check working directory
To know what is the location of current working directory, use the following command to find out. Just type,
If you are same as me using the Jupyter Notebook from their website, it shall be showing,
or it would a file location from your machine.
Besides that, we can import another handy command called exists. It returns True if path is an existing regular file or directory. Example:
import os.path os.path.isfile(fname) # Alternatively, using isfile() works the same and returns Boolean value # os.path.isfile(file_path)
Read a file
read() is used to read the content of a file. It returns all the contents in the file specified in the syntax. Example:
myfile = open('myfile.txt') myfile.read()
Because I asked to return everything in the file, it showed the whole strings with “\n“, an escape sequence. It is a indication, or we shall call it, delimiter, to tell me it is a newline in my text file.
If I run again the myfile.read(), its output is not the same anymore. Ops, why? It is because when it reads, it reads until end of the file. And, in Python, it has a cursor at the beginning of a file and when it reads it, it moves all the way to the end of a file.
I need to reset the cursor back to beginning of the file. How?
Reset the read cursor back to beginning of the file
It uses seek(0). Then, it goes back to the beginning and when I run again myfile = open(‘myfile.txt’), its output same as the 1st time I ran it.
This appears not exactly what we usually see in our browsers correct? I mean you do not want to have the “\n” in your strings correct?
Another read method in Python which reads exactly the format in the text file is using syntax,
Same way, I write,
It returns a list of elements. Below screenshot shows its difference between read() and readlines() with an example. To read the output of the readlines(), I can loop through the list and read each line. The “\n” is remained.
Read from different directory
If I am working on a different directory, I can specify the full file location path, as mentioned earlier. One important thing to take note is for Window, the file path has to use double backslash (“\\”) so Python does not treat the second “\” as an escape characters.
For Mac and Linux users, it uses the front slash, just opposite direction slash if you notice the different. Another easy way to rename a file location is using pwd, copy it and change.
Write into a file
I can write stuff into the file by using write() statement. It takes a parameter of a string I want to write to the file. Example:
myfile.write('This is a new added line from write() function.')
Close a file
It is good to make as a habit to close the unused file after reading it. One method we can go with is using the syntax:
It works like a File Save in the text editor. Sometimes, I will forget to close the file after reading it. Alternatively, there is another method of read and close a file without being missed out the close() syntax. Sample code below shows how to using with open() syntax:
#open, read and close the file with open('myfile.txt') as my_new_file: contents = my_new_file.read()
This codes allows the file to close without having to write, myfile.close(). Using the with … it shows the little indent on the second line. This means it will do whatever within this indent and close the file.
Summary of the day:
(Based on Jupyter Notebook)
- how to create a file.
- how to access a file.
- how to checking the working directory of a file.
- how to read, write and close a file.
- various modes used in the open() method.