Opening File Operation in Python

0 Comments

This tutorial is about how to open file in python.

Syntax: open(filename, mode)

We use open () function in Python to open a file in read or write mode.

Example:

f = open("abc.txt") # open file in current directory
f = open("C:/mydocs/abc.txt") # specifying full path

Open a file by specifying a mode.

f= open("abc.txt","w+") 

“w” is used for writing and will also create a file if it does not exist

file = open("myfile.txt", "r")
# a file named myfile, will be opened in reading mode
for data in file:
   print (data)# This will print every line one by one in the file

We can also specify encoding type when reading a file

f = open("test.txt", mode='r', encoding='utf-8')

Leave a Reply

Your email address will not be published. Required fields are marked *