File Handling in Python
Introduction
File handling in Python enables users to read and write files, besides various other file handling options. There is nothing required for importing an external library to read and write files in Python. It makes available an inbuilt function for creating, writing, and reading files.
The idea of file controlling has extended over diverse languages. This programming language has many distinctive features and functions to look out of files. It differentiates other high-level programming languages on the source of the structural organization of file management. It is simple to learn and appliance the coding module in Python. In this article, we would learn file handling in Python with depth.
Description
Opening a Text File in Python
We require to use the built-in open function to open a file.?The Python file open function yields a file object. That comprises methods and attributes to apply several operations for opening files in Python.
Syntax of Python open file function
file_object = open ("filename", "mode")
Example:
# a file named "tech", will be opened with the reading mode.
file = open('tech.txt', 'r')
# This will print every line one by one in the file
for each in file:
????print (each)
Creating a Text File in Python
We can create a .text files (tech.txt) by using the code with Write to file Python, we have confirmed here:
Open the .txt file
f= open("tech.txt","w+")
Enter data into the file
for i in range (10):
???? f.write("This is line %d\r\n" % (i+1))
领英推荐
Close the file instance
f.close()
Example:
# Python code to create a file
file = open('tech.txt','w')
file.write ("This is the write command")
file.write ("It enables us to write in a specific file")
file.close()
Appending to a File in Python
We may append or add a new text to the already present file or a new file.
f=open("tech.txt", "a+")
for i in range(2):
???? f.write ("Appended line %d\r\n" % (i+1))
This would write data into the file in append mode.
Reading Files in Python
Open the file in Reading mode
f=open ("tech.txt", "r")
if f.mode == 'r':
contents =f.read()
For more details visit:https://www.technologiesinindustry4.com/2021/12/file-handling-in-python.html