Sunday, October 25, 2020

Python Writing Files

Files are used for reading and writing text and binary data from files. Here will learn how to read, write and manage file resources efficiently. To perform any operation on files the file has to opened first. To open the file we use the built-in python open() function.
open function takes multiple arguments, most commonly used arguments are
file: path to the file to be opened
mode: mode in which the file is to be opened read/write/append and binary/text optional
encoding: Its better to define the encoding of the file, if no encoding is specified python will choose a  default encoding by sys.getdefaultencoding on that machine.

Now lets see how to write data to file using python programming.

 Character Meaning
 'r' Open for reading (default)
 'w' Open for writing, truncating the file if file exists with same name
 'a' Open for writing, append to the end of file if the file exists
 'b' binary mode
 't' text mode (default)

optional modes b,t can be combined with modes r,w,a. so resultant modes might be like 
rb : read binary
wb: write binary
ab : append binary
at  : append text
rt  : read text
wt : write text

fp = open('dummyfile.txt',  mode='wt',  encoding='utf-8')
fp.write('Programming helps to automate the process of manual work.')
fp.write('Automation makes work less error prone.\n')
fp.write('practice programming')
fp.close()

A file pointer fp is created to hold the file object that is opened using the open function, we passed file name, mode of the file and encoding of data in the file. Data is written to the file using the write function. Finally after completion of writing all the required data the file pointer has to be released, this is done by calling close function on the file object.


Number that is displayed after each write function above is the number of bytes that is written to the file.

Download the code from GitHub







No comments:

Post a Comment

Operations on Python Dictionaries