File I/O with Python

nurfitri
File I/O with Python

Reading data from Text file.

In python, we use the open() function to open a file programmatically. This function takes few arguments such as file path and read mode, then returns a File Object. If the file cannot be opened, it throw an OSError to us.

The mode mentioned specified the mode of which the file is opened.

  • r for read,
  • w for write,
  • a for appending,
  • b for binary mode,
  • t default text mode.
  • r+ read and write to a file.

The file object contains metadata about the file including its content. To read the content, we can use the .read() method.

For example, I have a text file named notes.txt.

jun@b:~$ ls
notes.txt fileio.py

To read the content of the text file, in my fileio.py I write these line of code

file = open("notes.txt") # open the file
print(file.read()) # read from it
file.close() # close the file

Running the code, we see the content of notes.txt printed on the terminal:

jun@b:~$ python3 fileio.py
This is my notes on python file I/O

Cursor

When Python reads a file, it uses a cursor to read from start to end. When we open the file, the cursor is at the beginning, and when we call .read(), the cursor reads and moves to the end. If we call the .read() method twice, the second call will yield nothing as the cursor is already at the end of the file.

file = open("notes.txt") # open the file
filecontent1 = file.read() # read from it, will print something
filecontentNext = file.read() # will return nothing, cursor at end

print("F1: {}".format(filecontent1))
print("FNext :{}".format(filecontentNext))
file.close() # close the file

The result will be this,

jun@b:~$ python3 fileio.py
F1: This is my notes on python file I/O

FNext:

Moving the cursor.

To move our cursor around, we can use the .seek() method to set the cursor position.

The seek method takes the character index as parameter. Lets say from the text content of our notes.txt, the 0 index is the beginning of the file, the 6th index is the letter s as highlighted in

" This is my notes on python file I/O "

using our previous code, we can re-read the content of our file by using the seek() method to move our cursor at the begining of the file.

file = open("notes.txt")

# first read
content = file.read()

#seek to begin
file.seek(0)

# second read
contentNext = file.read()
print("F1: {}".format(content))
print("FNext :{}".format(contentNext))
file.close() # close the file

Running it again, we can see that we are able to re-read the file

jun@b:~$ python3 fileio.py
F1: This is my notes on python file I/O

FNext :This is my notes on python file I/O

Using this new notes.txt example, we can also read our text file line by line using .readline() method.

This is my notes on python file I/O.
It is consist of multiple line text.
This is the third line of the text,
and every line are seperated by the new line character

The .readline() method will read our text one at the time, instead of moving the cursor all the way to the end.

file = open("notes.txt")
firstline = file.readline() # move cursor to end of 1st line
secondline = file.readline()

# read lines one by one and return as an array
restofthelines = file.readlines()

print("1st line: {}".format(firstline))
print("2nd line: {}".format(secondline))
print("rest lines: {}".format(restofthelines))

file.close()

Notices that I've used another method .readlines() that will read line where the cursor is until the end of the line, and return it as an array.

jun@b:~$ python3 fileio.py
1st line: This is my notes on python file I/O.

2nd line: It is consist of multiple line text.

rest lines: ['This is the third line of the text,\n', 'and every line are seperated by the new line character \n']

Read With

In python we can use with to easily open a file and read it with minimal code. The advantage of using with is that it automatically close our file whenever its finish reading the file.


with open("notes.txt") as file:
   print(file.read())

Write to file

Now lets try writing to our notes.txt. We can do this by passing the w arguments to the open() function. Then we can use the .write() to write to our file.

with open("notes.txt","w") as file:
    file.write("We write to a file using the `w` mode \n")
    file.write("To write a multi line text we end the line using the endline character '\\n' \n")
    file.write("Using 'w' will overide the original content \n")

Noticed that running the script above will override the content of our notes.txt file.

jun@b:~$ cat notes.txt

We write to a file using the `w` mode
To write a multi line text we end the line using the endline character '\n'
Using 'w' will override the original content

To append a text to a file we can use the a mode.

with open("notes.txt","a") as file:
    file.write("Here, we append a line to the text \n")
    file.write("Here is another line we append to the text \n")

this will append what we wrote to the end of the line of our text file.

jun@botbot:~$ python3 appendio.py
jun@botbot:~$ cat notes.txt

We write to a file using the `w` mode
To write a multi line text we end the line using the endline character '\n'
Using the 'w' will override the original content
Here, we append a line to the text
Here is another line we append to the text

Noted, that append will only, add the line to the end, we have no control over the cursor to add where we want to write our text.

To enable us to use cursor and write to a specific place in the text, we need to use r+ mode. This mode however will add our text to the beginning instead of the end of our file. It also will overide the text from the cursor position 0.

with open("notes.txt","r+") as file:
    # we can use file.seek() to any specific index if we want.
    file.write("Overide some words on first line")
jun@botbot:~$ python3 overide.py
jun@botbot:~$ cat notes.txt

Overide some words on first line mode
To write a multi line text we end the line using the endline character '\n'
Using the 'w' will overide the original content
Here, we append a line to the text
Here is another line we append to the tex

Look at our first line, some of the words get overide by the line we write. This thing is complicated and I hate it.

Close the file

Please remember to close the connection to our file, It can caused serious security issues if we forgot to close a file in our program.

We can check if our file is closed or open using the .closed attribute. this attribute is true if our file is closed.

file = open("notes.txt")
print(file.closed) # print false

file.close()
print(file.closed) #print true