UNIT – 6
File Handling and Dictionaries
As the part of programming requirement, we have to store our data permanently for the future purpose for this requirement we should go for files.
Files are very common permanent storage areas to store our data.
Types of files: These are 2 types of files
1) Text Files:
Usually, we can use those files to store character data.
2) Binary Files:
Usually, we can use binary files to store binary data like images, video files, audio files etc.
Before performing any operation (read or write) on the file, first, we have to open that file.
File handing Modes:
1) ‘R’ - Open an existing file for reading operation if the specified file does not exist then we will get file not found error. This is a default mode.
2) ‘W’ - Open an existing file for write operation if the file holds some data then it will be overridden, if the specified file does not exist then ‘w’ mode will create that file.
3) ‘A’ - Open an existing file for append operation it won’t override existing data. If the specified file is not already available then ‘a’ mode will create that new file.
4) ‘Rt’ - To read and write data into the file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file.
5) ‘Wt’ - To write and read data it will override existing data.
6) ‘At’ - To append and read data from the files it won’t override existing data.
7) ‘X’ - To open a file in exclusive creation mode for a write operation, if the file already exits thus we will get file exist error
Closing File: After completing the required operation on the file it is highly recommended to close the file.
For this, we have to use close() function
Eg: f.closr()
Reading data from text files:
We can use the following methods to read text from text files:
read() - to read total data from file
read(n)- to read n char from a file
Read line()- to read only one line
Read line()- to read at lines into a list
Eg)
Code: Read all data
F = open(‘abc:txt’,’r’)
Data = f.read()
print(data)
f.close()
Output: Contents of ‘abc.txt’ will be printed
Eg)
code read lines:
F = open(‘abc.txt’,’r’)
Lines =f.read lines()
For line in lines:
Print (line,end = “ “)
F.close ()
Writing Data to text files:
We can write character data to text files by using the following 2 methods.
1)Write (str)
2)Writelines ( list of lines)
Eg: f=open(‘xyz.txt’,’w’)
f.write(‘SAE In’)
f.write(‘Kondhwa In’)
f.write(‘Pune’)
print(‘data are written successfully’)
f.close()
Note: In the given code, data present in the file will be overridden every time if w run the program. Instead of overriding if we want append operation then we should open the file as follows.
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key: value pair. Key value is provided in the dictionary to make it more optimized.
Note – Keys in a dictionary doesn’t allow Polymorphism.
Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key: value. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and must be immutable.
# Creating a Dictionary |
# with Integer Keys |
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} |
print("\nDictionary with the use of Integer Keys: ") |
print(Dict) |
|
# Creating a Dictionary |
# with Mixed keys |
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} |
print("\nDictionary with the use of Mixed Keys: ") |
print(Dict) |
Adding and updating
In Python Dictionary,
Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by defining value along with the key
e.g. Dict[Key] = ‘Value’.
Updating an existing value in a Dictionary can be done by using the built-in update() method. Nested key values can also be added to an existing Dictionary.
Note- While adding a value, if the key value already exists, the value gets updated otherwise a new Key with the value is added to the Dictionary.
# Creating an empty Dictionary |
Dict = {} |
print("Empty Dictionary: ") |
print(Dict) |
|
# Adding elements one at a time |
Dict[0] = 'Greeks' |
Dict[2] = 'For' |
Dict[3] = 1 |
print("\nDictionary after adding 3 elements: ") |
print(Dict) |
|
# Adding set of values |
# to a single Key |
Dict['Value_set'] = 2, 3, 4 |
print("\nDictionary after adding 3 elements: ") |
print(Dict) |
|
# Updating existing Key's Value |
Dict[2] = 'Welcome' |
print("\nUpdated key value: ") |
print(Dict) |
Accessing
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
# Python program to demonstrate
# accessing a element from a Dictionary
# Creating a Dictionary
Dict = {1: 'Greeks', 'name': 'For', 3: 'Greeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using key
print("Accessing a element using key:")
print(Dict[1])
Design for Industrial Light and Magic(ILM):
Python was not designed just as a replacement for shell scripting and, as it turns out, Python enabled much more for ILM than just process control.
Feature:
Unlike Unix shell scripting, Python can be embedded whole as a scripting language within a larger software system. In this case, Python code can invoke specific functions of that system, even if those functions are written in C or C++. And C and C++ code can easily make calls back into Python code as well.
Use:
Using this capability, ILM integrated Python into custom applications written in C or C++, such as ILM's in-house lighting tool, which is used to place light sources into a 3D scene and to facilitate the writing, generation, and previewing of shaders and materials used on CG elements. It is the lighting tool that is ultimately responsible for writing the 3D scene out to a format that a renderer can interpret and render.
At the same time, more and more components, such as those responsible for ILM's many custom file formats and data structures, were re-wrapped as Python extension modules
Efficiency:
As Python was used more widely, extending and customizing in-house software became a lot easier. By writing in Python, users could recombine wrapped software components and extend or enhance standard CG applications needed for each new image production run. This let ILM staff to do exactly what a production needed at any given time, whether that meant allowing for a specific look for an entire show, or just a single CG character or element.
As it turned out, even some of ILM's non-technical users were able to learn enough Python to develop simple plug-ins and to create and modify production control scripts along side the technical users.
Reference Books
- R. G. Dromey, “How to Solve it by Computer”, Pearson Education India; 1st edition, ISBN-10: 8131705625, ISBN-13: 978-8131705629 Maureen Spankle, “Problem Solving and Programming Concepts”, Pearson; 9th edition, ISBN-10: 9780132492645, ISBN-13: 978-0132492645
- Romano Fabrizio, “Learning Python”, Packt Publishing Limited, ISBN: 9781783551712, 1783551712
- Paul Barry, “Head First Python- A Brain Friendly Guide”, SPD O’Reilly, 2nd Edition, ISBN:978-93-5213-482-3
- Martin C. Brown, “Python: The Complete Reference”, McGraw Hill Education, ISBN-10: 9789387572942, ISBN-13: 978-9387572942, ASIN: 9387572943
- Jeeva Jose, P. Sojan Lal, “Introduction to Computing & Problem Solving with Python”, Khanna Computer Book Store; First edition, ISBN-10: 9789382609810, ISBN-13: 978-9382609810