0% found this document useful (0 votes)
2 views

File IO Handling and Exception Handling.

The document provides an overview of file input/output handling and exception handling in Python, detailing how to read keyboard input using functions like raw_input and input. It explains various file operations including opening, reading, writing, renaming, and deleting files, as well as managing directories using the os module. Additionally, it covers file modes, attributes, and methods for reading and writing data to files.

Uploaded by

prasad wadkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

File IO Handling and Exception Handling.

The document provides an overview of file input/output handling and exception handling in Python, detailing how to read keyboard input using functions like raw_input and input. It explains various file operations including opening, reading, writing, renaming, and deleting files, as well as managing directories using the os module. Additionally, it covers file modes, attributes, and methods for reading and writing data to files.

Uploaded by

prasad wadkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

File I/O Handling and Exception Handling.

Reading Keyboard Input

Python provides two built-in functions to read a line of text from standard input,
which by default comes from the keyboard. These functions are −

 raw_input
 input

The raw_input Function

The raw_input([prompt]) function reads one line from standard input and returns it
as a string (removing the trailing newline).
#!/usr/bin/python

str = raw_input("Enter your input: ")


print "Received input is : ", str
This prompts you to enter any string and it would display same string on the screen.
Enter your input: Hello Python
Received input is : Hello Python

1)input(prompt): The input(prompt) function allows user input.It Takes one argument.

Syntax:input(prompt).

Where prompt is a string,representing a default message before the input.

Eg:For input(prompt)method

x=input(“Enter name:”)

Print(“hello,” +x)

Output:Enter name:bvjniot

Hello,bvjniot

2)input():This function input() always evaluate the input provided by user and return same
type data.If the input is integer type then its return integer value.If input value is string type
its return string value.

Syntax:x=input()

Eg:For reading input from keyboard

>>>x=input()
10

>>>Type(x)

<class ‘int’>

Files
File is a named location on disk to store related information.

Before performing any operation on the file like read or write, first we have to
open that file. For this, we should use Python’s in built function open() to
open a file.
This function creates a file object,as its is used to read or modify the file.

Syntax: fileobject=open(filename,acces_ mode)


Where:
Filename:this contain name of the file that we want to
access.
Access_mode: This determines the mode in which the file has
to be opened, i.e read,write,append etc.It is
optional,default argument argument is read(r)

Different Modes of Opening File.


r.No Modes & Description
.

1 r
Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.

2 w
Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.

3 a
Opens a file for appending. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
4 r+
Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

5 w+
Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading
and writing.

6 . a+
Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.and
File pointer points at the beginning

7 rb
Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode.

8 wb
Opens a file for writing only in binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing

9 ab
Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.

10 rb+
Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
11 wb+
Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing.

12 ab+
Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.

The text mode returns strings while reading from the file.The default is reading in the text
mode.

The binary mode returns bytes and used when dealing with non-text files like images or
executable files.

Eg:

f=open(“test.txt”,’r’)

f=open(“test.txt”,’w’)

f=open(“test.txt”,’a’)

Accessing File Content using Standard Library Functions.

The file Object Attributes


Once a file is opened and you have one file object, you can get various information
related to that file.
Here is a list of all attributes related to file object −
Sr.No. Attribute & Description

1 file.closed
Returns true if file is closed, false otherwise.

2 file.mode
Returns access mode with which file was opened.

3 file.name
Returns name of the file.

4 file.encoding
The encoding of the file

Example:
Reading Data From File

The read() method in python programming reads the contents of the file.It returns the
characters read from the file.

Example: Abc.txt file is created in same folder


Following 3 methods available for reading data purpose.

1)read(n) method:

The read () method just output the entire file if number of bytes are not given in the
argument.

Eg:f=open(“abc.txt”,”r”)

print(f.read(5))

print(f.read(5))

print(f.read())

2)readline(n)
The readline() method just output the entire line whereas readline(n) output at most n
bytes of a single line of a file.It doesn’t read more than one line.

3)readlines(): This method maintains a list of each line in the file.

Writing Data to Files


1)write(string) method:

The write() method writes any string to an open file.We need to be careful with the “w” mode
as it will overwrite into file if it already exist all previous data will get erased.

2)write(list) method:

It writes a sequence of strings to the file.


Closing File

When we are done with operations to the file,we need to properly close the file.

Syntax:file_object.close()

File Position:
The tell() is used to find the current position of the file pointer in the file
while the seek() is used to move the file pointer to the particular position.

Renaming a File:

To rename a file in python the OS module need to be imported.


The rename() method takes two arguments, the current filename and the
new filename.
Syntax: os.rename(current_file_name, new_file_name)
import os
print("Present Working Directory:",os.listdir())
os.rename("sample.txt","sam.txt")
print("Present Working Directory:",os.listdir())

Deleting a File:

To remove a file, the OS module need to be imported.


The remove() method is sued to remove the existing file with the file name.

Syntax: os.remove(filename)

Example:

import os

print("Present Working Directory:",os.listdir())

os.remove("sample.txt")
print("Present Working Directory:",os.listdir())

Directories
A Directory or folder is a collection of files and sub directories. The os module
has several methods that help you create, remove, and change directories

List Directory and Files:

All Files and subdirectories inside a directory can be known using listdir()
method

Syntax: os.listdir()

Eg: import os

print(os.listdir())

Create a New Directory:

We can make new directory using mkdir() method.

Syntax:os.mkdir(“newdir”)

Eg:

import os

os.mkdir("TYCM-Python")

print(os.listdir()).

Get Current Directory:

We can get the present working directory using getcwd() method..This method
returns the current working directory in the form of a string.

Syntax: os.getcwd()

Eg:

import os
print(os.getcwd())

Changing Directory

We can change the current working directory using the chdir() method.We can
used both forward slash as well as Backward slash to separate path elements.

import os

print(os.getcwd())

os.chdir(“d:\CM”)

print(os.getwd())

Removing Directory:

The rmdir() method is used to remove directory. Before removing a


directory, all the contents in it should be removed.If the directory is not
empty the we need to remove files first using os.remove() method
Syntax:os.rmdir(“dirname”)
Eg:

import os

print (os.listdir)

os.rmdir(“mydir”)

print(os.listdir())

You might also like