How to create, read and write contents to a file???

              In the computer world, a basic thing is called files. It contain set of instructions that can be a text,,image ,commands or any type of information. Generally, files can be of 3 types.

  • ·       System files
  • ·       Application files
  • ·       Data files

Based on the usage of information, it can be of any above type.

How to create file and write contents to the file in python:

              A file can  be created or created file can be opened by the following syntax.

File_object = open(“filename”,”mode”)

Where

File_object is the object from which, we access the file.

File name is the name of the file with extension.

Mode depends on the operations we perform on file.

Mode

Purpose

“x”

It creates a new file. If the file exists, this mode fails.

“b”

It represents binary mode.

“a”

It represents append mode.

“t”

It represents text mode.

“r”

Reading the file

“w”

Writing contents to the file.If the file exists, it writes the content.Else, it creates a new file.

“+”

It represents read and write operations.

 Let a example shown below.

#creates a file object(fo) and opens a file “sample.txt” with both reading and writing purpose

fo = open("sample.txt", "a+")

#create a for loop and prints hi message 5 times with number

for i in range(5) :

      fo.write("%d hi \n" %(i+1))

while executing this program, the user gets the following text in sample.txt.


How to read files in python ???

              It creates a file object using open method.

#open the file in read mode.

fo = open("sample.txt","r")

# check the mode and read using read method and write the contents using print()

if fo.mode == "r" :

   fc = fo.read()

   print(fc)

This program gives the below output.

These are the simple ways to create a file, read and write the contents.

No comments:

Post a Comment