Skip to main content

Python 3 Part 8 - File handling

 File handling in Python 3

Table of content

  1. File handling 
  2. Open method
  3. Modes
  4. Reading a file
  5. Writing to a file 
  6. Creating a new file

File Handling

We can handle different file handling operations in Python.  General steps for file handling is open a file, do read/write/append operations on the file and close the file.

Open function

open(<file_name>,<mode>) : Open function takes two parameters filename and mode.

Modes

r : open a file for read
w : open a file for write
a : open a file for append
r+ : open a file for read and write
rb : open a file for binary read (media files)
wb : open a file for binary write
ab : open a file for binary append
rb+ : open a file for binary read and write
x  : create new file

Reading a file

file.read() - read method reads the entire file content. Assume you have a demofile.txt with some content as below.

 Our python program to read the file.
When we run the code you see below output.
We can also specify the number of characters to be read. Below explain reads one character and print it to output stream.

Read file by line

file.readline() - method reads the content of the file line by line. We can looping through the contents of the file and process them. Below explain we are print the contents to the console.

Writing to a file

file.write("appended text") -  method is used to write to a file. The file is opened in either append or write mode. 

Below example in append mode, which adds the new content to existing content of the file at the end.


The file is opened in write mode. It will overwrite the existing contents of the file.

Create a new file

To create new file, we can use the create mode x 

Thank you folks. If you like this Python 3 post, please do checkout my other post on  Django with Python 3 series

Most viewed

Ruby on rails part 6 - Blocks , lambda, procs and closure

 Blocks , lambda, procs  and closure Table of content  1. Blocks 2. Lambda 3. Procs 4. Closure Blocks  Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or between brackets {} 
. Blocks can have multiple arguments
. The argument names are defined between two pipe | characters. Blocks are typically used with ‘each’ method which iterates over a list. Syntax of block using {} ['List of items'].each { | block arguments|  block body }  Syntax of block using do-end ['List of items'].each do | block arguments |      # block body end Example of block declared as do-end with each method.   [ 1 , 2 , 3 ].each do |num| puts num end     Output   $ ruby block_with_each.rb 1 2 3 $    Blocks can also be saved in variables or passed as argument to another function.   yield is a Ruby keyword that is used to call a block. When you use the yield keyword, the code inside the block will run. Example of saving a bl