Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

File Objects in Python



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

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

File Operations

The file is a named location on the disk to store related information, as the file is having some name and location, it is stored in the hard disk. In Python, file operation is performed in the following order -

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

Opening a File Using the 'open()' function

To open a file for both reading and writing, we must use the built-in open() function. The open() function uses two arguments. First is the name of the file and second is the mode (reading or, writing). The syntax to open a file object in Python is -

File_obj = open("filename", "mode")

Python File Modes

Once a file is opened, the file mode can be specified. For example, If we want to add append mode "a", to the file, write "w" or read "r". In addition, we have the option to open the file in binary mode or text format. Following are the different modes supported in the open() function -

Mode Description
?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)

Create a text file

Let's create a simple text file in Python using any text editor. In the following example, a new file is created in our current working directory, and on opening the newly created file.

# 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")

f.write("\nThis is our first line")

f.write("\nThis is our second line")

f.write("\nWhy writing more?, Because we can :)")

f.close()

Output

Reading a Text file

There are various ways to read a text file in Python, some of them are as follows below.

  • Extracting all characters of a string

  • Reading certain numbers of character

  • Reading a file line by line

  • Looping over a file object

  • Splitting Lines in a Text File

Extracting all characters of a string

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

file.read()

Example

Below is a program to implement the above syntax:

f = open("textfile.txt", "r")
f.read()

Output

'Hello, Python\nThis is our first line\nThis is our second line\nWhy writing more?, Because we can :)'

Reading certain numbers of character

If you want to read a certain number of characters in the string from a file, we can use the method as shown below -

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

Output

Hello, Python

Reading a file line by line

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

Example

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

Output

Hello, Python

This is our first line

This is our second line

Why writing more?, Because we can :)

Looping over a file object

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

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

Output

Hello, Python

This is our first line

This is our second line

Why writing more?, Because we can :)

Splitting Lines in a Text File

We can split the lines taken from a text file using the Python split() function. We can split our text using any character of your choice it can either be a space character 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!']

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. We can use the open() method to append data to an existing file. Use the EOL character to start a new line after you write data to the file.

Example

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

f.close()
f = open("textfile.txt", "r")
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 :).

Closing a file

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

Example

f = open("textfile.txt", "r")
f.close()
f.readlines()

Output

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

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

Using "with" Statement

The with statement can be used with file objects. Using the two (with statement & file objects) we get, much cleaner syntax and exception 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:

In this example, the file is automatically closed at the end of the with block, so there is no need to call the close() method explicitly.

with open("example.txt", "w") as file:
   file.write("This is an example using the with statement.")
   print ("File closed successfully!!")

Output

File closed successfully!!
Updated on: 2024-10-09T14:26:27+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements