Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Absolute File Name:: Unit-V Files, Modules and Packages Files

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Unit-V

Files, Modules and Packages


Files:
File is a named location on disk to store related information. It is used to permanently store data
in a non-volatile memory (e.g. hard disk).

Absolute file name:


A file name can specify all the directory names starting from the root of the tree, then it is
called an absolute file name.
It is defined as a filename that includes all of the path elements to get to the file from the root of
the volume.
Example:c:\python\unit5.txt
C:/python is referred as directory path
Relative file name:
It is realative to the current working directory. The complete directory path for a relative
filename is omitted.
Example:unit5.txt.
Types of files:
i) text file
II) Binary file
Text file:
A file that can be processes using text editor such as notepad is called text file. Text files
are stored in a form that is human-readable.
Text files are structured as a sequence of lines, where each line includes a sequence of
characters.
Binary file:
A binary file is a file stored in binary format.a binary file is computer-readable but not
human readable.
All executable programs are stored in binary files.
OPENING A FILE:
A file object that is associated with physical file is created.
Syntax:
file_variable=open(finename,mode)
The open function returns the file object for filename.
The mode parameter is a sring that specifies how the file will be used(either read or
write)
Modes:

S.No. Modes Description

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

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

Opens a file for both reading and writing. The file pointer placed at the
3 r+
beginning of the file.

Opens a file for both reading and writing in binary format. The file pointer
4 rb+
placed at the beginning of the file.

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

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

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

Opens a file for both writing and reading in binary format. Overwrites the
8 wb+ existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.

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

Opens a file for appending in binary format. The file pointer is at the end of
10 ab 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.

Opens a file for both appending and reading. The file pointer is at the end of
11 a+ 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.

Opens a file for both appending and reading in binary format. The file
12 ab+ 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.

Write():
The write() method writes any string to an open file. It is important to note that Python
strings can have binary data and not just text.Syntax:
fileobject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example:
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
# Close opend file
fo.close()

The read() Method
The read() method reads a string from an open file. It is important to note that Python strings
can have binary data. apart from text data.
Syntax
fileobject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. 
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
Output:
Read String is : Python is
close() Method
The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Syntax
fileobject.close();

Example:
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
Output:
Name of the file: foo.txt

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
The rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
os.rename(current_file_name, new_file_name)
Example
import os
os.rename( "test1.txt", "test2.txt" )

The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted
as the argument.
Syntax
os.remove(file_name)
Example
import os
os.remove("text2.txt")
Testing for file’s existence:
The isfile function in the os.path module is used to determine whether a file exists or not.
Output will be based on file presence in the current directory.

Program:
Import os.path
File_name=input(“enter the file name:”)
If os.path.isfile(file_name):
Print(“File is already exists with same name”)
Else:
Print(“no file found at the name”)

Output:
Enter file name:unit5.txt
File is already exists with same name

Enter file name:unit4.txt


no file found at the name

Writing data:
This class contains the methods for reading and writing data and also for closing the file.

Operations Descriptions
read(number,int) returns the specified number of characters from
the file. if arguments are omitted the entire
remaining contents in the fle are read
readline() returns the next line of the file as a string
readlines() returns a list of remaining lines in the file
write(str) write the string to file
writeline(),writelines() returns a list of remaining lines in the file
close() closes the opened file

Python File methods:

Method Description

close() Close an open file. It has no effect if the file is already closed.

Separate the underlying binary buffer from the TextIOBaseand


detach()
return it.

fileno() Return an integer number (file descriptor) of the file.

flush() Flush the write buffer of the file stream.

isatty() Return True if the file stream is interactive.

Read atmost n characters form the file. Reads till end of file if it


read(n)
is negative or None.

readable() Returns True if the file stream can be read from.


Read and return one line from the file. Reads in at most nbytes
readline(n=-1)
if specified.

Read and return a list of lines from the file. Reads in at


readlines(n=-1)
most n bytes/characters if specified.

seek(offset,from=SEEK_SET Change the file position to offset bytes, in reference


) to from (start, current, end).

seekable() Returns True if the file stream supports random access.

tell() Returns the current file location.

Resize the file stream to size bytes. If size is not specified,


truncate(size=None)
resize to current location.

writable() Returns True if the file stream can be written to.

Write string s to the file and return the number of characters


write(s)
written.

writelines(lines) Write a list of lines to the file.

File object Attributes:

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.
Exception Handling:
Try: The try block lets you test a block of code for errors. It contains one or more statements
that could produce an exception. If any statement produces an exception, remaining statements in
the block are omitted and execution hops to except block.
Except: The except block lets you handle the error. If the except argument matches with type of
exception object, then exception is fixed and the statement in exception block will be executed.
Syntax:
Try:
Operations
…..
…..
Except exception1:
Statement…
….
Except exception2:
Statement…
….
Else
Execute the code
Eg:
try : 
    a = 3
    if a < 4 :
          # throws ZeroDivisionError for a = 3 
        b = a/(a-3)
          # throws NameError if a >= 4
    print "Value of b = ", b
  # note that braces () are necessary here for multiple exceptions
except(ZeroDivisionError, NameError):
    print "\nError Occurred and Handled"

Output:
Error Occurred and Handled
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them −
 Exception Handling − This would be covered in this tutorial. Here is a list standard
Exceptions available in Python: Standard Exceptions.
 Assertions − This would be covered in Assertions in Pythontutorial.
List of Standard Exceptions −

S.No Exception Name & Description


.

1 Exception
Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError
Raised when a floating point calculation fails.

8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.

9 AssertionError
Raised in case of failure of the Assert statement.

10 AttributeError
Raised in case of failure of attribute reference or assignment.

11 EOFError
Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.

12 ImportError
Raised when an import statement fails.

13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing
Ctrl+c.

14 LookupError
Base class for all lookup errors.

15 IndexError
Raised when an index is not found in a sequence.

16 KeyError
Raised when the specified key is not found in the dictionary.

17 NameError
Raised when an identifier is not found in the local or global namespace.

18 UnboundLocalError
Raised when trying to access a local variable in a function or method but
no value has been assigned to it.

19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.

20 IOError
Raised when an input/ output operation fails, such as the print statement
or the open() function when trying to open a file that does not exist.

21 IOError
Raised for operating system-related errors.

22 SyntaxError
Raised when there is an error in Python syntax.
23 IndentationError
Raised when indentation is not specified properly.

24 SystemError
Raised when the interpreter finds an internal problem, but when this error
is encountered the Python interpreter does not exit.

25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If
not handled in the code, causes the interpreter to exit.

26 TypeError
Raised when an operation or function is attempted that is invalid for the
specified data type.

27 ValueError
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.

28 RuntimeError
Raised when a generated error does not fall into any category.

29 NotImplementedError
Raised when an abstract method that needs to be implemented in an
inherited class is not actually implemented.

Assertion:
Assertions are statements that assert or state a fact confidently in your program. For example,
while writing a division function, you're confident the divisor shouldn't be zero, you assert
divisor is not equal to zero.
Assertions are simply boolean expressions that checks if the conditions return true or not. If it is
true, the program does nothing and move to the next line of code. However, if it's false, the
program stops and throws an error.
It is also a debugging tool as it brings the program on halt as soon as any error is occurred and
shows on which point of the program error has occurred.
Python assert Statement
Python has built-in assert statement to use assertion condition in the program. assertstatement
has a condition or expression which is supposed to be always true. If the condition is false assert
halts the program and gives an AssertionError.
Syntax for using Assert in Pyhton:
assert <condition>
assert <condition>,<error message>
In Python we can use assert statement in two ways as mentioned above.
1. assert statement has a condition and if the condition is not satisfied the program will stop
and give AssertionError.
2. assert statement can also have a condition and a optional error message. If the condition
is not satisfied assert stops the program and gives AssertionError along with the error
message.
Eg:
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)
mark1 = []
print("Average of mark1:",avg(mark1))
Output:
AssertionError

(i)Word Count:
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. The number of words in each line is counted using len() and the count variable is incremented.
6. The number of words in the file is printed.

Program:
fname = input("Enter file name: ")
 
num_words = 0
 
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Output:
data1.txt:
Contents of file:
Hello world
 

Enter file name: data1.txt


Number of words:
2

Copy file using Shutil module:


from shutil
import copyfile
source_file=input(“Enter source file name:”)
destination_file=input(“Enter the destination file name”)
copyfile(source_file,destination_file)
print(“File content copied”)
print
print(“contents of destination file”)
print
file_read=open(destination_file,”r”)
print(file_read.read())
file_read.close()
Output:
Enter source file name:
Enter the destination file name:
Source_file.txt
Hello world
File content copied
contents of destination file
destination_file.txt
Hello world

Copy file without using module:


source_file=input(“Enter source file name:”)
destination_file=input(“Enter the destination file name”)
source =( source_file,’r’)
destination =( destination_file,’w’)
for lines in source:
destination.write(line)
source.close()
destination.close()
print(“File content copied”)
print(“contents of destination file”)
file_read=open(destination_file,”r”)
print(file_read.read())
file_read.close()

Output:
Enter source file name:
Enter the destination file name:
Source_file.txt
Hello world
File content copied
contents of destination file
destination_file.txt
Hello world

You might also like