#5, First Floor, 4th Street , Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 pro@slogix.in

Office Address

  • #5, First Floor, 4th Street Dr. Subbarayan Nagar Kodambakkam, Chennai-600 024 Landmark : Samiyar Madam
  • pro@slogix.in
  • +91- 81240 01111

Social List

How to handle file using python?
Description

To see how to handle the files and its operations in python3.

Process

Open a file.

   Python has a built-in function open() to open a file.

   It is used to read or modify the file accordingly.

Modes of files(Mechanism).

  r------Opens a file for reading only(default)

   w------Opens a file for writing only

   rb-----Open a file for reading only in binary format

   rb+---Opens a file for both reading and writing in binary format

  wb----Opens a file for writing only in binary format

  wb+---Opens a file for both writing and reading in binary format

Close the file.

  When we are done with operations to the file, we need to properly close the file.

  File will be close by using Python close().

Sapmle Code

#read a file using loop and readlines()

#os package for detect the file directory

import os

os.chdir(‘/home/soft23/soft23/Sathish

/Pythonfiles’)

list=[]

for line in open(‘read_it.txt’,’r’).readlines():

list.append(line)

#slicing

list=list[0:10]

str1=”.join(list)

print(“—–Before writing the file—–“)

print(str1)

#writing the same file with new content

import os

os.chdir(‘/home/soft23/soft23/Sathish

/Pythonfiles’)

fo = open(“read_it.txt”, “w”)

fo.write( “Python is a great language.\nIts very easy to learn.\nPython has easy syntax\nIts very easy to learn”)

print(“File writting is heppening…”)

#close the file

fo.close()

#After writing the file

import os

os.chdir(‘/home/soft23/soft23/Sathish

/Pythonfiles’)

list=[]

for line in open(‘read_it.txt’,’r’).readlines():

list.append(line)

#slicing

list=list[0:10]

str1=”.join(list)

print(“—–After writing the file—–“)

print(str1)

(new_list1)

Screenshots