You are on page 1of 59

Files in Python

What is a File?
• Files are named locations on disk to store related information.
• They are used to permanently store data in a non-volatile
memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile, we use files for
future use of the data by permanently storing them.
• When we want to read from or write to a file, we need to open it
first.
• When we are done, it needs to be closed so that the resources
that are tied with the file are freed.
File Operations File1 File2

File1
Opening Files
• The key function for working with files is the open() function.
• This function returns a file object, also called a handle, as it is used to read
or modify the file accordingly.

f = open("test.txt")

To open file in current directory


Examples
f = open("test.txt")

To open file in current directory

f = open("C:/Python38/README.txt")

To open file by specifying full path


About accessing modes
• We can specify the mode while opening a file.
• In mode, we specify whether we want to
– read r,
– write w or f = open("test.txt", "w" )
– append a
• We can also specify if we want to open the file in
– text mode or
– binary mode.
• The default is reading in text mode. Here we get strings when reading from the file.
• Binary mode returns bytes and this is the mode to be used when dealing with non-
text files like images or executable files.
Access modes
• "x" - creates the specified file, returns an error if the file exists.
• "r" - opens a file for reading, error if the file does not exist. (default value)
• "w" - opens a file for writing. If the file already contains some data then it
will be overridden.
• "a" - opens a file for appending. Creates the file if does not exist.
• "r+" - opens a file to read and write data.
• "w+" - opens a file to write and read data. It will override existing data.
• "a+" - opens a file to append and read data.
Writing to Files
• There are two ways to write in a file.
• write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
• writelines() : For a list of string elements, each string is inserted
in the text file. Used to insert multiple strings at a single time.
L = [str1, str2, str3]
File_object.writelines(L)

• We must include the newline characters ourselves to distinguish


the different lines.
File_object.write(str1)
File_object.writelines(L)
Reading Files
• To read a file in Python, we must open the file in reading r mode.
• There are three ways to read data from a text file.
• read() : Returns the read bytes in form of a string. Reads n bytes, if no
n specified, reads the entire file.
s = File_object.read(n)
• readline() : Reads a line of the file and returns in form of a string. For
specified n, reads at most n bytes. However, does not reads more
than one line, even if n exceeds the length of the line.
s = File_object.readline(n)
• readlines() : Reads all the lines and return them as each line a string
element in a list.
lst = File_object.readlines()
s = File_object.read(n)
s = File_object.readline(n)
lst = File_object.readlines()
Append to a file
• To append a new line to a file in Python, we must open the file in append a mode.
• When the file is opened in append mode, the handle is positioned at the end of the file.
• The data being written will be inserted at the end, after the existing data.
File Operations (Read & Write) on Excel File
Append Sum of existing values in next cell
Random Access
• tell() - It tells you the current position within the file.
• seek(offset[, from]) - This method changes the current file position.
• The offset argument indicates the number of bytes to be moved.
• The from argument specifies the reference position.
• 0 - beginning of the file as the reference position
• 1 - current position as the reference position
• 2 - end of the file as the reference position.
Renaming Files
Python os module provides methods that help you perform
file-processing operations, such as renaming and deleting files.
rename() - It takes two arguments, the current filename and
the new filename.
Syntax: os.rename(current_file_name, new_file_name)
Deleting Files
Python os module provides methods that help you
perform file-processing operations, such as renaming
and deleting files.
remove() - This method is used to delete a file.
Syntax: os.remove(file_name)
Other Methods of File
Method Description
Separates the underlying binary buffer from the TextIOBase
detach()
and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
Resizes the file stream to size bytes. If size is not specified,
truncate(size=None)
resizes to current location.
writable() Returns True if the file stream can be written to.
readable() Returns True if the file stream can be read from.

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


Working in Google Colab
Open link https://colab.research.google.com/
Sign in with Google Account and open new notebook
Save notebook with a suitable name.
Mount drive using following code segment.
Click on Connect to Google Drive
It will ask us for login. Login to same google A/C
Click on Allow
Now Mounted at ‘/content/drive’
We can see MyDrive at \content\drive
We can access folders from our Drive by using path
✓Impost csv library
✓Open the csv file which is available in your Google Drive by specifying exact
path.

For Example:

import csv
csv_file = open('/content/drive/MyDrive/Colab Noteb
ooks/Datasets/student_data.csv')
Working with csv files in Python

What is a CSV ?
✓ CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet

or database.

✓ A CSV file stores tabular data (numbers and text) in plain text.

✓ Each line of the file is a data record. Each record consists of one or more fields, separated by commas.

✓ The use of the comma as a field separator is the source of the name for this file format.

✓ For working CSV files in python, there is an inbuilt module called csv.
Sample CSV File (student_data.csv)
csv.reader(csvfile, dialect='excel', **fmtparams)
Return a reader object which will iterate over lines in the given csv file
csv.reader(): read data from a csv file
Using next()
Return the next row of the reader’s iterable object as a list
(if the object was returned from reader()) or a dict (if it is a DictReader instance

Usually you should call this as next(reader).


We can also you use DictReader() to read CSV files as Dictionary.
7 a) Write a program that loads roll numbers
and names from the given CSV file into
dictionary where data is organized as one
row per record. It takes a roll number or
name as input and prints the corresponding
other value from dictionary.
import csv
path = '/content/drive/MyDrive/Colab Notebooks/Datasets
/studentNames.csv'
csv_file = open(path)
data = csv.DictReader(csv_file,delimiter=',')

print("You like to search with\n1.Roll Number or\n2.Name \n")


op=int(input())
value=input("Enter Value to search\n")

for row in data:


if op==1 and row["Name"]==value:
print(row["RollNo"])
if op==2 and row["RollNo"]==value:
print(row["Name"])
Writing CSV files in Python
csv.writer class
✓ csv.writer class is used to insert data to the CSV file.
✓ This class returns a writer object which is responsible for converting the
user’s data into a delimited string.
✓ A csv file object should be opened with newline='' otherwise newline
characters inside the quoted fields will not be interpreted correctly

writerObject = csv.writer(csvfile)
csv.writer class provides two methods for writing to CSV.
They are
1. writerow() and
2. writerows(). A List of fields

writerow(fields)
A nested List
(List of rows)
writerows(rows)
Python program to demonstrate writing to CSV
import csv # name of csv file
path = "university_records.csv"
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA'] # writing to csv file
with open(path, 'w') as csvfile:
# data rows of csv file # creating a csv writer object
rows = [ ['Nikhil', 'COE', '2', '9.0'], csvwriter = csv.writer(csvfile)
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'], # writing the fields
['Sagar', 'SE', '1', '9.5'], csvwriter.writerow(fields
['Prateek', 'MCE', '3', '7.8'], # writing the data rows
['Sahil', 'EP', '2', '9.1']] csvwriter.writerows(rows)
7 b) Write a program to find
the frequency of distinct
words in the given text file
and store the words along
with the frequency in a CSV
file.
import csv
path = '/content/drive/MyDrive/Colab Notebooks/Datasets/bhagat.txt'
text_file = open(path)
data =text_file.read().split()
text_file.close()
word_freq=[]
s=set(data)
s=list(s)
for i in s:
word_freq.append(data.count(i))
path = '/content/drive/MyDrive/Colab Notebooks/Datasets/ bhagat.csv'
f=open(path,"w")
write_obj=csv.writer(f)
write_obj.writerow(s)
write_obj.writerow(word_freq)
f.close()

You might also like