How to open and close a file in Python

There may rise a circumstance where one necessities to connect with outer documents with Python.Python gives inbuilt capacities to making, composing and understanding records.

We will examine how to open an outside record and close a similar utilizing Python.
As of not long ago, you have been perusing and keeping in touch with the standard info and result.

Presently, we will perceive how to utilize genuine information records. Python gives essential capacities and techniques important to control documents of course. You can do the greater part of the record control utilizing a document object.

File open and close in python

Python has an inherent capacity open() to open a record, it returns something many refer to as a document object. Record object contain techniques and qualities that can be utilized to gather data about the document you opened. They can likewise be utilized to control said record.

Opening a record in python:

There are two sorts of records that can be taken care of in Python, typical text documents and paired records (written in twofold language, 0s, and 1s). Opening a record alludes to preparing the document either for perusing or for composing. This should be possible utilizing the open() work. This capacity returns a record item and takes two contentions, one that acknowledges the document name and another that acknowledges the mode(Access Mode).

Note: The record should exist in a similar index as the Python script, any other way, full location of the document ought to be composed.

Syntax: File_object = open(“File_Name”, “Access_Mode”)

Parameters:

  • File_Name: It is the name of the file that needs to be opened.
  • Access_Mode: Access modes govern the type of operations possible in the opened file. The below table gives the list of all access mode available in python:
Operation Syntax Description
Read Only r Open text file for reading only.
Read and Write r+ Open the file for reading and writing.
Write Only w Open the file for writing.
Write and Read w+ Open the file for reading and writing. Unlike “r+” is doesn’t raise an I/O error if file doesn’t exist.
Append Only a Open the file for writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified.
Append and Read a+ Open the file for reading and writing and creates new file if it doesn’t exist. All additions are made at the end of the file and no existing data can be modified.

Example 1:
In this example, we will be opening a file to read-only. The initial file looks like below:

 

Python

Code:

Python3

# open the file using open() function
file = open("sample.txt")
  
# Reading from file
print(file.read())

Here we have opened the file and printed its content.

Output:

This is a sample text file for the example.

Example 2:

In this example, we will be appending new content to the existing file. So the initial file looks like below:

Python

Code:

Python3

# open the file using open() function
file = open("sample.txt", 'a')
  
# Add content in the file
file.write(" This text has been newly appended on the sample file")

Now if you open the file you will see the below result,

Output:

Python

Example 3:

In this example, we will be overwriting the contents of the sample file with the below code:

Code:

Python3

# open the file using open() function
file = open("sample.txt", 'w')
  
# Overwrite the file
file.write(" All content has been overwritten !")

The above code leads to the following result,

Output:

Python

Closing a file in Python:

Assuming you notice, we have not shut any of the records that we worked on in the above models.

However, Python consequently shuts a record assuming the reference object of the document is distributed to another document, it is a standard practice to close an opened record as a shut record lessens the danger of being unjustifiably adjusted or perused.

Python has a nearby() strategy to close a record. The nearby() strategy can be called at least a couple of times and on the off chance that any activity is performed on a shut record it raises a ValueError.

The underneath code shows a straightforward utilization of close() strategy to close an opened record.

Example 1:

Python3

# open the file using open() function
file = open("sample.txt")
  
# Reading from file
print(file.read())
# closing the file
file.close()

Now if we try to perform any operation on a closed file like shown below it raises a ValueError:

Python3

# open the file using open() function
file = open("sample.txt")
  
# Reading from file
print(file.read())
# closing the file
file.close()
# Attempt to write in the file
file.write(" Attempt to write on a closed file !")

Output:

ValueError: I/O operation on closed file.

Conclusion

Anybody working with Python will probably have to work with records widely. A fundamental piece of record collaboration is trying to close them when you have wrapped up!

Leaving documents open can create many issues, particularly in huge activities that depend on a wide scope of records.

As we’ve examined, a straightforward method for staying away from the entanglements that leaving records open might possibly cause is to open your documents utilizing a setting chief, which consequently closes records for you. Following this example will save you a task while forestalling squandered assets and adaptation irregularities. In particular, utilizing with explanations will assist with making your code look perfect and expert.

Also ReadHow to set checkbox size in HTML/CSS?

Leave a Reply

Your email address will not be published. Required fields are marked *