Part 9: Working with Files :

Part 9: Working with Files :

This is the continuation of series of blog post on getting started to data science using python(part 1,part 2,part 3,part 4,part 5,part 6,part 7,part 8) . So today will explore the building blocks of python with one of the most fundamental staff of reading and writing a file . Points to remember when accessing a file File path – String that represent the path where the file is kept Folder – the location of folder , sub folder separated by backslash (\) in python File Name– The Actual name of the file Extension – the end of the file name after (.) Accessing a file path : Absolute Path –An absolute path refers to same location of the file system regardless the current working directory . Eg :

Relative Path :File residing in some other working directory , do not need to be present in the current directory .

Opening and closing of file :

The same shortcut you can use in accessing a file .

With os.path. + tab

Opening a file in python :

If a file is open with WITHkeyword , closing of the file is automatically maintained .

Commonly used mode to access a file :


Open for reading (default)


Open for writing, truncating (overwriting) the file first

‘rb’ or ‘wb’

Open in binary mode (read/write using byte data)

Reading File :

Ways of reading a file :


This reads from the file based on the number of size bytes. If no argument is passed or None or -1 is passed, then the entire file is read.


This reads at most size number of characters from the line. This continues to the end of the line and then wraps back around. If no argument is passed or None or -1 is passed, then the entire line (or rest of the line) is read.


This reads the remaining lines from the file object and returns them as a list.

Write to a file :



This writes the string to the file.


This writes the sequence to the file. No line endings are appended to each sequence item. It’s up to you to add the appropriate line ending(s).

Example :

Try it yourself with a variety of example .

Happy Learning and sharing .

Instructor lead Online training in Datascience join our watsapp group

Upgrade your skills join our community

Leave a Reply

Close Menu