0% found this document useful (0 votes)
20 views5 pages

File-Handling in Python

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)
20 views5 pages

File-Handling in Python

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/ 5

File Handling in Python

Files – can be of two types:

- Text File: stores data as text using ASCII or Unicode character coding scheme. Each line
in file ends with newline character and each file ends with EOF character.

- Binary File: stores data in binary form, and is intended for a program to read. We cannot
view its contents with a text editor. Binary file also ends with EOF character.

We shall be working with text files in our context. Let’s first take few examples:

(i) Creating a new file and writing data to it:

outfile = open('countryList.txt', 'w') # opening file

outfile.write("USA\n") # writing to file


outfile.write("UK\n")
outfile.write("Canada\n")
outfile.write("Australia\n")

outfile.close() # closing file

(ii) Reading data from file:

infile = open('countryList.txt', 'r') # opening file

file_data = infile.read() # reading from file

print(file_data)

infile.close() # closing file

Opening the File: We open a file using file opening instruction, whose syntax is:

file_variable_name = open(filename , mode)

Here,

filename - is a file placed in some directory on hard-disk. We need to provide the


path to access the file – the path can be relative to the current working
directory or it can be the complete path from C drive. For example: to access a
file, named records.txt present in a path in C:\myFiles, we shall provide
filename as string – ‘C:\myFiles\records.txt’ - this is also referred to as
absolute filename (providing filename starting from root directory).

If the file is present in the same path as the path of python or the IDE that we
are working on, then we need not provide any path and just mentioning
filename will suffice! OR, if the file is present in any directory (already
existing) of that path, then we just need to specify that directory name
followed by filename. For example: records.txt exists in myFiles directory
inside spyder’s path, then we can access this file using: myFiles\records.txt –
we need not start from root C:\ - this is referred to as relative filename
(relative to the current path, which is spyder’s path here)

file_variable_name - is the corresponding file object for filename that we’ll be using
in the program to refer to the filename.

mode - is a string that specifies the mode in which file will be opened. Python
has following file-opening modes:

“r” : opens a file for reading only (no writing is possible!). This is
the default mode for opening a file – if no mode is specified, ‘r’ is
assumed by default. The file pointer is placed at the beginning of the
file.

“w” : opens a file for writing – if the file is already existing, its
contents will get erased. If the file doesn’t exist, it gets created!

“a” : opens the file in append mode – if the file exists, new data will
be written to the end of file as the file pointer is placed at the end of the
file. If the file doesn’t exist, it gets created!

“ r+ ” : opens the file for both reading and writing. The file pointer is
placed at the beginning of the file.

We can append “t” or “b” along with modes to indicate the type of file we’ll be working with.
For example – if we specify mode as “rb” then it indicates we are opening a binary file in
read mode. If neither of these specified, “t” or text file is assumed by default!

Example of using r+ mode:

outfile = open('C:\myFiles\countryList.txt', 'r+')


file_data = outfile.read()
print(file_data)
outfile.write("India\n")
outfile.close()
Closing the File:

Once we are done with the file, we should close it using:

file_variable_name.close()

Although, the file is automatically closed when the program ends but it is still a good practice
to do so explicitly. Failing to close the file in a large program could be problematic and may
even cause the program to crash because it will keep consuming the resources associated.

Writing Data to a File: There are two methods for writing data to a file:

1) write(string) - writes the input string to the file, syntax:

file_variable_name.write(string)

Example: outFile.write(“Hello!!”)

outFile.write(“and welcome!!”)

will write strings – Hello!! And welcome!! on the same line in the file referred to by
variable name, outFile.

If we want these two string to be written to different lines (new lines) in the file, we’ll
need to specify newline character(“\n”) after the string as:

outFile.write(“Hello!!\n”)

outFile.write(“and welcome!!”)

will result in writing following contents to file:

Hello!!
and welcome!!

2) writelines(sequence) - writes all strings in a sequence to the file, syntax:

file_variable_name.write(sequence)

Example:
lines = ["Hello World!\n", "Welcome to Python\n", "Python is fun"]
outFile.writelines(lines)
outFile.close()

will write the strings in the list, ‘lines’ to the file!


Reading Data from a File: There are three methods for reading data from a file:

1) read() - reads the input string from the file, syntax:

file_variable_name.read()

Example: reading countryList.txt using:

file_data = infile.read()

and, printing file_data will return the output as:

USA
UK
Canada

2) readline() - reads the single line of the string from the sequence written to the file,
Syntax:
file_variable_name.readline()

Example: reading the file that has ‘lines’ sequence written to it using:

firstline = infile.readline()
print(firstline)

secondline = infile.readline()
print(secondline)

will return the output as:

Hello World!

Welcome to Python

NOTE:

A better way to print the file contents is to use loop:

for line in infile:


print(line)

and, the output will remain the same:

Hello World!

Welcome to Python
3) readlines() - reads all the lines from the sequence written to the file and returns the
list of the lines from the file, syntax:

file_variable_name.readlines()

Example: reading the file that has ‘lines’ sequence written to it using:

line_seq = infile.readlines()
print(line_seq)

will return the output as:

['Hello World!\n', 'Welcome to Python\n', 'Python is fun\n']

File-object attributes:

1. file_variable_name.closed – returns if file is closed

2. file_variable_name.mode – returns the mode in which file is opened

3. file_variable_name.name – returns actual file-name

Exercise – 1: Write a program that reads a file line by line and finds the count of vowels
present on the input text file.

You might also like