Open a File for Read and Write

Python File Handling

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 will learn:

  • How to Open a Text File in Python
  • How to Create a Text File in Python
  • How to Append 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 need to apply the built-in open role. The Python file open part returns a file object that contains methods and attributes to perform various operations for opening files in Python.

Syntax of Python open up file role

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

Here,

  • filename: gives proper noun of the file that the file object has opened.
  • manner: aspect of a file object tells you which mode 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 create a .text files (guru99.txt) by using the code, nosotros accept demonstrated here:

Footstep 1) Open the .txt file

f= open("guru99.txt","w+")
  • We declared the variable "f" to open a file named guru99.txt. Open takes ii arguments, the file that nosotros want to open and a string that represents the kinds of permission or operation we want to do on the file
  • Here, we used "w" alphabetic character in our statement, which indicates Python write to file and information technology volition create file in Python if it does not exist in library
  • Plus sign indicates both read and write for Python create file operation.

Step 2) Enter data into the file

for i in range(10):      f.write("This is line %d\r\n" % (i+1))
  • We have a for loop that runs over a range of ten numbers.
  • Using the write function 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 role so percent d (displays integer)
  • And then basically we are putting in the line number that nosotros are writing, then putting it in a carriage return and a new line character

Step 3) Close the file instance

f.close()
  • This will shut the instance of the file guru99.txt stored

Hither is the result later code execution for create text file in Python case:

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 example "guru99.txt" information technology will look something similar this

How to Create a Text File in Python

Example of how to create a text file in Python


How to Append Text File in Python

Yous can besides append/add a new text to the already existing file or a new file.

Stride one)

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

In one case again if you could see a plus sign in the code, information technology indicates that information technology volition create a new file if it does non exist. Just in our instance we already accept the file, so we are not required to create a new file for Python append to file operation.

Step two)

for i in range(two):      f.write("Appended line %d\r\due north" % (i+1))

This will write data into the file in suspend mode.

How to Append Text File in Python

How to Append Text File in Python

You tin see the output in "guru99.txt" file. The output of the code is that earlier file is appended with new data by Python suspend to file functioning.

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 tin can read a file in Python past calling .txt file in a "read style"(r).

Stride 1) Open the file in Read mode

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

Step 2) We employ the mode function in the code to cheque that the file is in open mode. If yes, we proceed alee

if f.manner == 'r':

Step 3) Utilise 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 example:

How to Read Files in Python

How to Read Files in Python


How to Read a File line by line in Python

You can as well read your .txt file line by line if your data is likewise big to read. readlines() code will segregate your data in piece of cake to read mode.

How to Read a File line by line in Python

How to Read a File line past line in Python

When you run the code (f1=f.readlines()) to read file line by line in Python, information technology volition carve up each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read way. But if there is a complex data file which is non readable, this slice of lawmaking could be useful.

File Modes in Python

Post-obit are the diverse File Modes in Python:

Mode Description
'r' This is the default mode. It Opens file for reading.
'west' This Mode Opens file for writing.
If file does not be, information technology creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the performance fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default style. Information technology opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)

Here is the consummate code for Python print() to File Instance

Python 2 Example

def main():      f= open up("guru99.txt","due west+")      #f=open("guru99.txt","a+")      for i in range(10):          f.write("This is line %d\r\n" % (i+ane))      f.close()         #Open up 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 ten in fl:      #print 10 if __name__== "__main__":   main()

Python 3 Instance

Below is another Python print() to File Case:

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.close()     #Open the file back and read the contents     #f=open("guru99.txt", "r")     #if f.way == '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__":   main()

Summary

  • Python allows y'all to read, write and delete files
  • Utilise the function open("filename","west+") 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, use the control open up("Filename", "a")
  • Use the Python read from file function to read the ENTIRE contents of a file
  • Apply the readlines function to read the content of the file one by one.

brannonjohispent.blogspot.com

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

0 Response to "Open a File for Read and Write"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel