File Objects in Python?

PythonServer Side ProgrammingProgramming

In python, whenever we try read or write files we don’t need to import any library as it’s handled natively.

The very first thing we’ll do is to use the built-in open function to get a file object.

The open function opens a file and returns a file object. The file objects contains methods and attributes which latter can be used to retrieve information or manipulate the file you opened.

What is a file?

Before we do any operation on file, let’s first understand what is file? File is a named location on disk to store related information, as the file is having some name and location, it is stored in hard disk.

In python, file operation is performed in following order:

  • Opening a file.
  • Read or Write operation.
  • Closing a file.

Opening a file- Open() function

In order to open a file for reading or writing purposes, we must use the built-in open() function.

The open() function uses two arguments. First is the name of the file and second is for what purpose we want to open it .i.e. for reading or writing?

The syntax to open a file object in python is:

File_obj = open(“filename”, “mode”)

Where

  • File_obj also called handle is the variable to add the file object.

  • filename: Name of the file.

  • mode: To tell the interpreter which way the file will be used.

>>> f = open("pytube1.py") # open file in current directory
>>> f = open(r"c:\users\rajesh\Documents\readme.txt") # Open file from the given path

Mode argument

As we can see from above, giving second argument to the open() function is optional which is mode. We can specify the mode while opening a file .i.e. whether we want to read ‘r’, write ‘w’ or append ‘a’ to the file. We can also specify if we want to open the file in text mode or binary mode.

The default mode is text mode where we get strings when reading from the file.

Below are the different modes supported in open() function:

Python File Modes

ModeDescription
‘r’Open a file for reading. (default)
‘w’Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘x’Open a file for exclusive creation. If the file already exists, the operation fails.
‘a’Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
‘t’Open in text mode. (default)
‘b’Open in binary mode.
‘+’Open a file for updating (reading and writing)
>>> f = open("pytube1.py") #equivalent to 'r' or 'rt'
>>> f = open("pytube1.py", "w")# write in text mode
>>> f = open("color3.jpg", "r+b")# read and write in binary mode

The default encoding is platform dependent. In windows, it is ‘cp1252’ but ‘utf-g’ in linux.

It is recommended to specify the encoding type:

>>> f = open("pytube1.py", mode = "r", encoding = 'utf-8')

Create a text file

Let’s create a simple text file in python using any text editor or your choice, though I’m using python shell ☺.

>>> # Create a text file named "textfile.txt" in your current working directory
>>> f = open("textfile.txt", "w")
>>> #above will create a file named textfile.txt in your default directory
>>> f.write("Hello, Python")
13
>>> f.write("\nThis is our first line")
23
>>> f.write("\nThis is our second line")
24
>>> f.write("\nWhy writing more?, Because we can :)")
37
>>> f.close()

We can see a new file is created, named textfile.txt in our current working directory and on opening the newly created file, we see something like:

Reading a Text file in Python

To read a text file in python, we can use multiple ways.

In case you want to extract a string that contains all characters in the file. We can use the following method:

file.read()

Below is program to implement above syntax:

>>> f = open("textfile.txt", "r")
>>> f.read()
'Hello, Python\nThis is our first line\nThis is our second line\nWhy writing more?, Because we can :)'

In case you want to read certain numbers of character from a file, we can do it very easily.

>>> f = open("textfile.txt", "r")
>>> print(f.read(13))
Hello, Python

However, if you wanted to read a file line by line then you can use the readline() function.

>>> f = open("textfile.txt", "r")
>>> print(f.read(13))
Hello, Python
>>> print(f.readline())

>>> f = open("textfile.txt", "r")
>>> print(f.readline())
Hello, Python

>>> print(f.readline())
This is our first line

>>> print(f.readline())
This is our second line

>>> print(f.readline())
Why writing more?, Because we can :)

Or you want to return every line in the file, properly separated, we could use the readlines() function.

>>> f = open("textfile.txt", "r")
>>> print(f.readlines())
['Hello, Python\n', 'This is our first line\n', 'This is our second line\n', 'Why writing more?, Because we can :)']

Above each line is comma separated.

Looping over a file object

In case you want to read or return all the lines from the file in a most structured and efficient way, we can use the loop over method.

>>> f = open("textfile.txt", "r")
>>> for line in f:
print(line)

Hello, Python

This is our first line

This is our second line

Why writing more?, Because we can :)

Writing to a file

Writing to a file is simple, you just need to open the file and pass on the text you want to write to a file.

This method we can use to append data to an existing file. Use EOL character to start a new line after you write data to the file.

>>> f = open("textfile.txt", "w")
>>> f.write("There are tons to reason to 'fall in love with PYTHON'")
54
>>> f.write("\nSee, i have added one more line :).")
36
>>> f.close()
>>> f = open("textfile.txt", "r")
>>> for line in f:
print(line)

There are tons to reason to 'fall in love with PYTHON'
See, i have added one more line :).

Closing a file

Once you’re done with working on file, you have to use the f.close() command to end things. With this, we’ve close the file completely, terminating all the resources in use and freeing them up for the system to use elsewhere.

>>> f = open("textfile.txt", "r")
>>> f.close()
>>> f.readlines()
Traceback (most recent call last):
File "<pyshell#95>", line 1, in <module>
f.readlines()
ValueError: I/O operation on closed file.

Once the file is closed, any attempt to use the file object will through an error.

With Statement

The with statement can be used with file objects. Using the two (with statement & file objects) we get, much cleaner syntax and exceptions handling in our program.

Another advantage is that any files opened will be closed automatically once we are done with file operations

Syntax

with open(“filename”) as file:

Example:

>>> with open("textfile.txt") as f:
for line in f:
   print(line)

Output

There are tons to reason to 'fall in love with PYTHON'

See, i have added one more line :).

Writing to a file using with statement is also easy (as you’ve guessed by now).

>>> with open("textfile.txt", "a") as f:
f.write("\nHello, Python-Here i come once again!")

38
>>> with open("textfile.txt") as f:
for line in f:
print(line)


There are tons to reason to 'fall in love with PYTHON'

See, i have added one more line :).

Hello, Python-Here i come once again!

Splitting Lines in a Text File

We can split the lines taken from a text file using python split() function. We can split our text using any character of your choice it can either be a space character or colon or something else.

>>> with open("textfile.txt", "r") as f:
data = f.readlines()
   for line in data:
      words = line.split()
      print(words)

Output

['There', 'are', 'tons', 'to', 'reason', 'to', "'fall", 'in', 'love', 'with', "PYTHON'"]
['See,', 'i', 'have', 'added', 'one', 'more', 'line', ':).']
['Hello,', 'Python-Here', 'i', 'come', 'once', 'again!']

And we are going to split the text using a colon instead of a space(like above), we just need to change line.split() to line.split(“:”) and our output will be something like:

["There are tons to reason to 'fall in love with PYTHON'\n"]
['See, i have added one more line ', ').\n']
['Hello, Python-Here i come once again!']
raja
Published on 09-Apr-2019 06:47:51
Advertisements