Reading and Writing Text Files in Python
Python File Treatment
In Python, there is no need for importing external library to read and write files. Python provides an inbuilt role for creating, writing, and reading files.
In this file handling in Python tutorial, we volition learn:
- How to Open up a Text File in Python
- How to Create a Text File in Python
- How to Suspend Text File in Python
- How to Read Files in Python
- How to Read a File line by line in Python
- File Modes in Python
How to Open a Text File in Python
To open a file, you lot demand to use the built-in open
part. The Python file open function returns a file object that contains methods and attributes to perform various operations for opening files in Python.
Syntax of Python open up file office
file_object = open("filename", "mode")
Here,
- filename: gives proper name of the file that the file object has opened.
- mode: attribute of a file object tells you which fashion a file was opened in.
More than details of these modes are explained below
How to Create a Text File in Python
With Write to file Python, y'all can create a .text files (guru99.txt) by using the code, nosotros have demonstrated here:
Step ane) Open up the .txt file
f= open("guru99.txt","w+")
- Nosotros declared the variable "f" to open a file named guru99.txt. Open takes 2 arguments, the file that nosotros want to open and a cord that represents the kinds of permission or performance we want to practice on the file
- Here, we used "west" alphabetic character in our argument, which indicates Python write to file and it will create file in Python if it does not exist in library
- Plus sign indicates both read and write for Python create file operation.
Footstep 2) Enter data into the file
for i in range(10): f.write("This is line %d\r\n" % (i+one))
- We have a for loop that runs over a range of 10 numbers.
- Using the write part to enter data into the file.
- The output we want to iterate in the file is "this is line number", which we declare with Python write file function then pct d (displays integer)
- And so basically we are putting in the line number that we are writing, and so putting it in a carriage return and a new line grapheme
Pace 3) Close the file instance
f.close()
- This will close the case of the file guru99.txt stored
Here is the result after code execution for create text file in Python example:
When you click on your text file in our example "guru99.txt" information technology will look something like this
How to Append Text File in Python
You can as well suspend/add a new text to the already existing file or a new file.
Step 1)
f=open("guru99.txt", "a+")
Once more if you could see a plus sign in the lawmaking, information technology indicates that information technology will create a new file if information technology does not exist. Simply in our case we already have the file, and so we are not required to create a new file for Python append to file operation.
Stride ii)
for i in range(ii): f.write("Appended line %d\r\n" % (i+ane))
This will write data into the file in append mode.
You can come across the output in "guru99.txt" file. The output of the lawmaking is that earlier file is appended with new data by Python append to file functioning.
How to Read Files in Python
You tin read a file in Python by calling .txt file in a "read way"(r).
Step 1) Open the file in Read way
f=open up("guru99.txt", "r")
Step 2) We utilize the style function in the lawmaking to cheque that the file is in open mode. If yep, nosotros go along ahead
if f.mode == 'r':
Footstep three) Use f.read to read file data and shop it in variable content for reading files in Python
contents =f.read()
Step 4) Print contents for Python read text file
Here is the output of the read file Python case:
How to Read a File line by line in Python
You tin can also read your .txt file line by line if your information is likewise big to read. readlines() code will segregate your data in piece of cake to read mode.
When you lot run the lawmaking (f1=f.readlines()) to read file line by line in Python, it will separate each line and nowadays the file in a readable format. In our instance the line is brusk and readable, the output volition look similar to the read manner. Merely if in that location is a complex data file which is not readable, this slice of code could be useful.
File Modes in Python
Following are the diverse File Modes in Python:
Mode | Description |
---|---|
'r' | This is the default mode. It Opens file for reading. |
'w' | This Mode Opens file for writing. If file does not be, it creates a new file. If file exists it truncates the file. |
'x' | Creates a new file. If file already exists, the functioning fails. |
'a' | Open up file in suspend mode. If file does not exist, it creates a new file. |
't' | This is the default fashion. It opens in text manner. |
'b' | This opens in binary style. |
'+' | This will open a file for reading and writing (updating) |
Here is the complete code for Python impress() to File Example
Python 2 Example
def main(): f= open("guru99.txt","w+") #f=open("guru99.txt","a+") for i in range(ten): f.write("This is line %d\r\due north" % (i+1)) f.close() #Open the file back and read the contents #f=open("guru99.txt", "r") # if f.fashion == 'r': # contents =f.read() # print contents #or, readlines reads the individual line into a list #fl =f.readlines() #for 10 in fl: #print 10 if __name__== "__main__": main()
Python 3 Example
Below is some other Python impress() to File Case:
def primary(): f= open("guru99.txt","west+") #f=open("guru99.txt","a+") for i in range(10): f.write("This is line %d\r\northward" % (i+1)) f.close() #Open up the file back and read the contents #f=open("guru99.txt", "r") #if f.manner == 'r': # contents =f.read() # print (contents) #or, readlines reads the individual line into a list #fl =f.readlines() #for x in fl: #impress(x) if __name__== "__main__": main()
Summary
- Python allows you to read, write and delete files
- Use the office open("filename","w+") for Python create text file. The + tells the python interpreter for Python open text file with read and write permissions.
- To suspend data to an existing file or Python print to file operation, employ the command open("Filename", "a")
- Use the Python read from file function to read the ENTIRE contents of a file
- Use the readlines function to read the content of the file one by ane.
Source: https://www.guru99.com/reading-and-writing-files-in-python.html
0 Response to "Reading and Writing Text Files in Python"
Post a Comment