CBSE CS and IP

CBSE Class 11 & 12 Computer Science and Informatics Practices Python Materials, Video Lecture

Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Files Opening Modes in Python File Handling

encode() String Function

encode() The string encode() method returns encoded version of the given string.
Since Python 3.0, strings are stored as Unicode, i.e. each character in the string is represented by a code point. So, each string is just a sequence of Unicode code points.

For efficient storage of these strings, the sequence of code points are converted into set of bytes. The process is known as encoding. There are various encodings present which treats a string differently. The popular encodings being utf-8, ascii, etc. By default, Python uses utf-8 encoding.

decode() String Function

This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.

Read Mode (r, r+, rb, rb+)

  • Read pointer moves as we read in the file. If we give.
  • In r+ mode read and write pointer move together.
  • In rb mode the data is read in the Bytes format.

Write Mode (w, w+, wb, wb+)

  • We can write only strings not numbers.
  • Write-Pointer Moves as we write in the file.
  • “w+” create a new file and overwrite if file already
  • existing. “r+” overwrite characters not file.
  • To write in the binary mode the string should be
  • converted into bytes format using (bytes() or encode() orusing b ’ ‘)

Append Mode (a, a+, ab, ab+)

  • Pointer will be at the end when we open the file. So, a+ and ab+ will not read anything if we want to read using them.
  • After Opening file, If we write anything it will write at the
  • end.

File Object Attributes

Python’s open() function creates a file object which serves as a link to the file residing on your
computer.

File Object Methods

File Object Methods (read)


Read Functions

read()

  • read() will read full file at once and move the file pointer at the end.
  • read(n) , will read n bytes from it’s current position.

readline()

  • readline() reads one line at a time. It searches “\n” and read the file till “\n”.
  • If I use readline(n), then it read the n bytes or upto “\n” (whichever comes first) from current position.

readlines()

  • Read all the lines in the list.
  • readlines(n), reads all lines where nth bytes is present.

File Object Methos (write)

Write Function

write(<string>)

This will write given string in the file and the pointer moves as we write into the file.

writelines(<list>)

  • Using this function we can give list of lines to write into the file.
  • The important thing to remember here is you have to give ‘\n’ manually at the end of eachline in the list to tell the python to write it into separate lines.
  • Ex:- [‘1st Line \n’, ‘2nd Line \n’, ‘3rd Line’]

File Object Methods (seek & tell)

File Object Methods (seek & tell)

seek() :

<file_obj>.seek(<Offset>,<from_where>)
<from_where> options 1 & 2 does not work with text file if <offset> is other than 0.

Read file character by character


Question:

Count the Number of Characters?

Read file word by word

Question:

Count the number of particular word.?

Read file line by line

Question:

Count the number of lines in the file ?

General Errors during file Handling

1.While writing integers -> TypeError: write() argument must be str, not int

  • We can write only string in file handling
  • If we need to write integers, we have to convert it into strings using type casting

2.While writing in Binary File -> TypeError: a bytes-like object is required, not 'str‘

  • In Binary files only Binary data can be written.
  • We have to convert the string data to bytes format using, bytes() function.




File Handling in Python - an Introduction

File Handling in Python - an Introduction

What is a file?

  • Every file in the computer is just a series of bytes, which is arranged one after the other.
  • All the bytes are of 8 bits, Hence each byte is a number between 0 and 255.
  • As we discussed in the above point, every file consists of bytes. So, each file can be considered as a binary file.  
  • But if the file contains bytes for only text (characters, numbers, and other symbols) that everyone uses for general purpose, then the file can be considered as a text file.

Types of Files

Binary Files – A binary file is just a file that contains information in the same format in which the
information is held in memory.

Text Files - Text files can be considered as a subset of binary files. That is used to store human-readable characters as RTF (rich text file) or plain text document. Text files are of two types:-
  • Plain text files (.txt)
  • Rich text files (.rtf)
CSV Files (Comma Separated Values) – A Comma Separated Values (CSV) file is a simple text file that contains data as comma-separated values. CSV files can be used for exporting and importing the data between different applications. For example, we can transfer data between databases and Python Pandas using CSV. 



Absolute and Relative Path of Files

Absolute Path – It is a full path of the file from the root directory.
Ex : - C:\Users\Tanmay\Desktop\Delete\file handling.txt

Relative Path – It is the path of the file from the current working directory.
Ex: -If I am on Desktop then the relative Path for file “file handling.txt” is .\Delete\file handling.txt

Operation on files in python

1.Opening a file– open() function
2.Read/Write file–
                 – Read Functions – read() , readline(), readlines()
                 – Write Functions – write() , writelines()
3.Close the File – close() Function
4.Remove the file – remove() Function of OS Module

Read the contents of an existing file

1.Open the file– 
file_object = open(“read_sample.txt”, ’r’) # Relative Path
file_object = open(“C:\Desktop\Notes\sample.txt”) #Absolute Path

2.Reading the file– 
rf = file_object.read()
print(rf)

3.Closing the file– 
file_object.close()