0% found this document useful (0 votes)
19 views6 pages

UNIT-4 NOTES python programming

Uploaded by

riddhijain1003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views6 pages

UNIT-4 NOTES python programming

Uploaded by

riddhijain1003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

Notes on Python Programing

UNIT 4: PYTHON FILE OPERATION:

Why we need files?:


● While a program is running, its data is in memory.
● When the program ends, or the computer shuts down, data in
memory disappears.
● To store data permanently, you have to put it in a file.
● Files are usually stored on a hard drive, floppy drive, or
CD-ROM.
● Working with files is a lot like working with books.
● To use a book, we have to open it. When we’re done, we have
to close it.
● While the book is open, you can either write in it or read from
it.

Example:
Opening a file creates a file object. In this example, the
variable f refers to the new file object.
>>> f = open("test.dat","w")
>>> print f
The open function takes two arguments. The first is the name of
the file, and the second is the mode. Mode "w" means that we are
opening the file for writing.

● In Python a file operation take place in the following order:


1. Open a file
2. Read or write
3. Close the file

Opening Text Files :


● All files must first be opened before they can be read from
or written to.
● In Python, when a file is (successfully) opened, a file object is
created that provides methods for accessing the file.
● We look at how to open files for either reading (from) or
writing (to) a file.

modes of opening a file:


● r – open for reading
● w - open for writing
● a - open for appending
● + - open for updating.
● ‘rb’ will open for reading in binary mode.
● ‘rt’ will open for reading in text mode.

1. Opening for Reading:


● To open a file for reading, the built-in open function is
used as shown,

input_file = open('myfile.txt', 'r')

● The first argument is the file name to be opened,


'myfile.txt'.
● The second argument, 'r', indicates that the file is to be
opened for reading. (The second argument is optional
when opening a file for reading.)
● If the file is successfully opened, a file object is created
and assigned to the provided identifier, in this case
identifier input_fi le.
● When opening a file for reading, there are a few
reasons why an I/O error may occur.
● First, if the file name does not exist, then the program
will terminate with a “no such file or directory” error.

2. Opening for Writing :


● To open a file for writing, the open function is used as
shown below,
output_file = open('mynewfile.txt','w')
● Note that, in this case, 'w' is used to indicate that the
file is to be opened for writing.
● If the file already exists, it will be overwritten (starting
with the first line of the file).
● When using a second argument of 'a', the output will be
appended to an existing file instead.
● It is important to close a file that is written to, otherwise
the tail end of the file may not be written to the file
(discussed below),

output_file.close()
● When opening a file for writing, there is not much
chance of an I/O error occurring.
● The provided file name does not need to exist since it is
being created (or overwritten).
● Thus, the only error that may occur is if the file system
(such as the hard disk) is full.

Reading Text Files:


● In Python we have following way to read a file using read( )
function

f = open("this.txt", "r") # Open the file in read mode


text = f.read( ) # Read its contents
print(text) # Print its contents
f.close ( ) # Close the file

readline( ):
● We can also use the f.readline( ) function to read one
full line at a time.
● The readline method returns as a string the next line of
a text file, including the end-of-line character, \n.
● When the end-of-file is reached, it returns an empty
string as demonstrated in the while loop:

input_file = open('myfile.txt','r')
empty_str = ‘ ‘
line = input_file.readline( )
while line != empty_str :
print((line)
line = input_file.readline( )
input.close( )

● It is also possible to read the lines of a file by use of the for


statement,
input_file = open('myfile.txt','r')
for line in input_file:
readlines():
● readlines() is used to read all the lines at a single go and
then return them as each line a string element in a list.
● This function can be used for small files, as it reads the
whole file content to the memory, then splits it into
separate lines.
● We can iterate over the list and strip the newline ‘\n’
character using strip() function.

f = open("file.txt", "r+") # Open a file


print("Name of the file: ", f.name)

# Assuming file has following 5 lines


# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = f.readlines( )
print("Read Line: ", line)
f.close() # Close opened file

Output:
Name of the file: f.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is
4th line\n', 'This is 5th line']

NOTE: Using a for statement, all lines of the file will be read one
by one. Using a while loop, however, lines can be read until a
given value is found.

Writing Text Files:


● In order to write to a file, we first open it in write or append
mode, after which, we use python's write( ) method to write to the
file.

f = open("this.txt", "w") # Open the file in write mode


f.write("this is nice") # Write a string to the file
f.close( ) # Close the file
WITH Statement: The best way to open and close the file
automatically is the with statement.
# Open the file in read mode using 'with', which automatically
closes the file
With open("this.txt", "r") as f: # Read the contents of the file
text = f.read()
print(text) # Print the contents

writelines() function:
● This function writes the content of a list to a file.

Syntax:
# write all the strings present in the list "list_of_lines"
# referenced by file object.
file_name.writelines(list_of_lines)

● As per the syntax, the list of strings that is passed to the writelines()
function is written into the opened file.
● Similar to the write() function, the writelines() function does not add a
newline character(\n) to the end of the string.

Example:
file1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')

file1.writelines(lst)
file1.close()
print("Data is written into the file.")

You might also like