Read From Text File and Write Back in Text File Python

Python File Treatment

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing, and reading files.

In this file treatment in Python tutorial, we will larn:

  • 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 up a file, you need to use the born open function. The Python file open office returns a file object that contains methods and attributes to perform various operations for opening files in Python.

Syntax of Python open up file function

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

Here,

  • filename: gives name of the file that the file object has opened.
  • mode: attribute of a file object tells you which style a file was opened in.

More details of these modes are explained below

How to Create a Text File in Python

With Write to file Python, you tin can create a .text files (guru99.txt) by using the code, nosotros have demonstrated here:

Step 1) Open the .txt file

f= open up("guru99.txt","due west+")
  • We alleged the variable "f" to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a cord that represents the kinds of permission or functioning we want to do on the file
  • Here, we used "w" letter of the alphabet in our argument, which indicates Python write to file and it will create file in Python if information technology does non be in library
  • Plus sign indicates both read and write for Python create file operation.

Step two) Enter data into the file

for i in range(10):      f.write("This is line %d\r\due north" % (i+1))
  • We accept a for loop that runs over a range of ten numbers.
  • Using the write function to enter data into the file.
  • The output nosotros want to iterate in the file is "this is line number", which we declare with Python write file function and then percentage d (displays integer)
  • Then basically we are putting in the line number that we are writing, and then putting it in a carriage return and a new line character

Step 3) Close the file instance

f.close()
  • This volition close the example of the file guru99.txt stored

Here is the result afterward code execution for create text file in Python example:

How to Create a Text File in Python

How to Create a Text File in Python

When you click on your text file in our instance "guru99.txt" information technology will expect something like this

How to Create a Text File in Python

Case of how to create a text file in Python


How to Append Text File in Python

You can also suspend/add a new text to the already existing file or a new file.

Footstep 1)

f=open("guru99.txt", "a+")

Once again if you could come across a plus sign in the code, it indicates that information technology will create a new file if it does non be. Only in our instance we already have the file, so nosotros are not required to create a new file for Python append to file operation.

Step 2)

for i in range(ii):      f.write("Appended line %d\r\north" % (i+one))

This will write information into the file in suspend mode.

How to Append Text File in Python

How to Append Text File in Python

You can meet the output in "guru99.txt" file. The output of the code is that before file is appended with new information by Python append to file operation.

Example of How to Append Text File in Python

Example of How to Append Text File in Python

How to Read Files in Python

You can read a file in Python by calling .txt file in a "read way"(r).

Footstep 1) Open the file in Read manner

f=open up("guru99.txt", "r")

Step ii) We utilize the style office in the code to check that the file is in open mode. If yes, we proceed ahead

if f.mode == 'r':

Step 3) Apply f.read to read file information 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 instance:

How to Read Files in Python

How to Read Files in Python


How to Read a File line by line in Python

You can also read your .txt file line by line if your data is besides large to read. readlines() code volition segregate your data in easy to read mode.

How to Read a File line by line in Python

How to Read a File line by line in Python

When y'all run the code (f1=f.readlines()) to read file line by line in Python, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output volition look similar to the read mode. Only if at that place is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python

Following are the various File Modes in Python:

Style 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 information technology truncates the file.
'x' Creates a new file. If file already exists, the performance fails.
'a' Open file in append mode.
If file does non be, it creates a new file.
't' This is the default mode. It opens in text style.
'b' This opens in binary fashion.
'+' 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 up("guru99.txt","w+")      #f=open("guru99.txt","a+")      for i in range(10):          f.write("This is line %d\r\n" % (i+ane))      f.shut()         #Open the file back and read the contents      #f=open("guru99.txt", "r")      #   if f.mode == 'r':       #     contents =f.read()      #     print contents      #or, readlines reads the individual line into a list      #fl =f.readlines()      #for x in fl:      #print x if __name__== "__main__":   chief()

Python three Case

Beneath is another Python print() to File Example:

def master():     f= open("guru99.txt","w+")     #f=open("guru99.txt","a+")     for i in range(10):          f.write("This is line %d\r\north" % (i+1))     f.close()     #Open the file back and read the contents     #f=open("guru99.txt", "r")     #if f.mode == 'r':     #   contents =f.read()     #    print (contents)     #or, readlines reads the individual line into a list     #fl =f.readlines()     #for x in fl:     #print(x) if __name__== "__main__":   primary()

Summary

  • Python allows y'all to read, write and delete files
  • Utilize the function open up("filename","due west+") for Python create text file. The + tells the python interpreter for Python open text file with read and write permissions.
  • To append information to an existing file or Python print to file functioning, utilize the control open("Filename", "a")
  • Utilize the Python read from file function to read the Entire contents of a file
  • Utilize the readlines function to read the content of the file one by ane.

daviswhall1967.blogspot.com

Source: https://www.guru99.com/reading-and-writing-files-in-python.html

0 Response to "Read From Text File and Write Back in Text File Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel