Working with files in Python!


19 Jul 2018

views: 270


blog cover image

Python provides us many different ways to read and write to a file. Here we will see how to use them and how they works.

The easiest way to open a file is to use the python open() function. While opening a file in the same directory where the script is we use open('file1.txt', 'w'). To open a file file in specific directory we can provide the raw location lik open(r'D:\python_files\file1.txt', 'w').

There are few options while opening a file shown below:


Mode Description
'r' Opens a file in read only mode
'w' Opens a file if already exists also clears its contents, if not creates a new file
'x' Creates a new file, error in case of file already exists
'a' Opens file in append mode, If not exist creates a new file
't' To open a file in text mode. Also its a default mode
'b' Open a file in binary mode
'+' Open a file in both read and write mode.

Here is an example:


def f_w():
    infile = open('file1.txt', 'w')
    print(infile.read())
def f_x():
    infile = open('file2.txt', 'x')
    print(infile.read())
def f_a():
    infile = open('file3.txt', 'a')
    print(infile.read())
def f_t():
    infile = open('file4.txt', 't')
    print(infile.read())
def f_b():
    infile = open('file5.txt', 'b')
    print(infile.read())
def f_wp():
    infile = open('file6.txt', 'w+')
    print(infile.read())
def f_ap():
    infile = open("file7.txt", "a+")
    print(infile.read())

f_w()
f_x()
f_a()
f_t()
f_b()
f_wp()
f_ap()


Try the code and see what will be the output. Comment below if you found what will be the result.




Thank you for Subscribing! We will make sure you never miss a thing.



author-avatar

Om Prakash Mahato

Full stack developer, author, founder of TechConductor.


0 Comments:


    Leave a comment:


    Name is ok.
    Comment is ok.
    Email is ok.
    Website is ok.