The document discusses Python dictionaries. Some key points:
- A dictionary in Python is an unordered collection of key-value pairs where keys must be unique and immutable, while values can be any data type.
- Dictionaries are created using curly braces {} and keys are separated from values with colons.
- Elements can be accessed, added, updated, and deleted using keys. Nested dictionaries are also supported.
- Common operations include creating, accessing, modifying dictionaries as well as nested dictionaries. User input can also be used to update dictionary values.
This document provides information on file handling and dictionaries in Python. It discusses file paths, opening and closing files, reading from and writing to files. It also covers creating, accessing, adding, updating and deleting elements in dictionaries. Finally, it discusses directory methods like getcwd(), chdir(), listdir(), mkdir(), rmdir() and rename() for working with directories in Python.
The document discusses files in Python. It defines a file as an object that stores data, information, settings or commands used with a computer program. There are two main types of files - text files which store data as strings, and binary files which store data as bytes. The document outlines how to open, read, write, append, close and manipulate files in Python using functions like open(), read(), write(), close() etc. It also discusses pickling and unpickling objects to binary files for serialization. Finally, it covers working with directories and running other programs from Python.
This document provides an overview of functions and file handling in Python. It discusses defining user-defined functions with the def keyword, including passing arguments, default arguments, keyword arguments, and variable number of arguments. It also covers recursion, anonymous functions, and attributes of file objects. For file handling, it explains opening, reading, writing, and appending files, as well as the different file modes.
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
This document provides an introduction to learning Python. It discusses prerequisites for Python, basic Python concepts like variables, data types, operators, conditionals and loops. It also covers functions, files, classes and exceptions handling in Python. The document demonstrates these concepts through examples and exercises learners to practice char frequency counting and Caesar cipher encoding/decoding in Python. It encourages learners to practice more to master the language and provides additional learning resources.
File Handling Topic for tech management you know na tho kyuon puch raha hai saleRohitKurdiya1
The document discusses various file handling methods in Python like open(), read(), write(), readline(),readlines() and close(). It explains that open() is used to open a file and return a file object. The different modes of open() like 'r', 'w', 'a' are used to read, write and append files. Methods like read() reads the entire file content, readline() reads one line, readlines() returns a list of lines. write() is used to write content to a file in 'w' or 'a' mode. close() closes the file after operations.
The document discusses reading from and writing to files in Python. It describes the write() and read() methods for writing strings to and reading from open files. It also covers opening files with different modes like "a" for append and "w" for overwrite. Examples are given to illustrate writing a line of text to a file, reading the first 10 bytes of a file, and reading each line of a file using a loop.
The document provides an introduction to programming in Python. It discusses how Python can be used for web development, desktop applications, data science, machine learning, and more. It also covers executing Python programs, reading keyboard input, decision making and loops in Python, standard data types like numbers, strings, lists, tuples and dictionaries. Additionally, it describes functions, opening and reading/writing files, regular expressions, and provides examples of SQLite database connections in Python projects.
The document provides an overview of Python lists:
- Lists allow you to store sets of information in a particular order and are one of Python's most powerful features.
- You can define lists using square brackets and commas, and use plural names for lists to make code more readable. Lists can contain millions of items.
- Lists allow adding, inserting, removing, sorting, and accessing elements by their position or value using various list methods like append(), insert(), remove(), sort(), and indexing.
- Loops like for loops efficiently iterate through lists to work with each element.
Beginners python cheat sheet - Basic knowledge O T
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
File handling in Python allows programs to read from and write to files stored on the file system. There are different modes for opening files, such as read ("r"), write ("w"), and append ("a"). Common file operations include reading, writing, updating, deleting, and creating files. Files can be opened, read from and written to, then closed. Python supports various data types that can be read from or written to files, such as text, binary, images, and audio files. File handling is an important part of building applications that need to persist data.
Python is a widely used high-level programming language. It can be used for general purpose programming and scripting. Python code can run on many operating systems. The document discusses Python data types like numbers, strings, tuples, lists, and dictionaries. It also covers Python methods, operators, control flow statements, functions, modules, packages, and object-oriented programming concepts like classes.
Files and directories can be manipulated in Python using various functions. Files are opened, read from and written to using methods like open(), read(), write() and close(). Directories can be created, listed, changed and deleted using os module functions like mkdir(), listdir(), chdir() and rmdir(). File operations involve opening, performing read/write and closing the file.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending to add an item, inserting to add an item at a specific index, removing items, sorting lists, finding the length of a list, and accessing items by index.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data handling techniques.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data structures.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending items, inserting items, removing items, sorting lists, finding the length of a list, and accessing items by index. Lists provide a powerful way to organize and work with sets of data in Python.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
The document discusses dictionaries in Python. It explains that a dictionary is a collection of unordered key-value pairs where keys must be unique. Keys can be strings, numbers, or tuples, while values can be any data type. Dictionaries allow accessing values using keys. Common dictionary operations include adding/updating items, checking if a key exists, getting values, and looping through keys and key-value pairs. The document also provides examples of using dictionaries to count word frequencies in a text file by parsing and removing punctuation.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This document provides an overview of file handling in Python. It begins by outlining learning objectives related to understanding different file types, opening and closing files, and reading from and writing to files. It then discusses the need for data file handling to permanently store program data. Various file types are introduced, including text files, CSV files, and binary files. Methods for opening, reading from, writing to, and closing both text and binary files are described. The pickle module is explained for pickling and unpickling Python objects for storage in binary files. Finally, random access methods like tell() and seek() are briefly covered.
The document provides an introduction to programming in Python. It discusses how Python can be used for web development, desktop applications, data science, machine learning, and more. It also covers executing Python programs, reading keyboard input, decision making and loops in Python, standard data types like numbers, strings, lists, tuples and dictionaries. Additionally, it describes functions, opening and reading/writing files, regular expressions, and provides examples of SQLite database connections in Python projects.
The document provides an overview of Python lists:
- Lists allow you to store sets of information in a particular order and are one of Python's most powerful features.
- You can define lists using square brackets and commas, and use plural names for lists to make code more readable. Lists can contain millions of items.
- Lists allow adding, inserting, removing, sorting, and accessing elements by their position or value using various list methods like append(), insert(), remove(), sort(), and indexing.
- Loops like for loops efficiently iterate through lists to work with each element.
Beginners python cheat sheet - Basic knowledge O T
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
The document provides an overview of common Python data structures and programming concepts including variables, strings, lists, tuples, dictionaries, conditionals, functions, files, classes, and more. It includes examples of how to define, access, modify, loop through, and perform operations on each type of data structure. Key points covered include using lists to store ordered sets of items, dictionaries to store connections between pieces of information as key-value pairs, and classes to define custom object types with attributes and methods.
File handling in Python allows programs to read from and write to files stored on the file system. There are different modes for opening files, such as read ("r"), write ("w"), and append ("a"). Common file operations include reading, writing, updating, deleting, and creating files. Files can be opened, read from and written to, then closed. Python supports various data types that can be read from or written to files, such as text, binary, images, and audio files. File handling is an important part of building applications that need to persist data.
Python is a widely used high-level programming language. It can be used for general purpose programming and scripting. Python code can run on many operating systems. The document discusses Python data types like numbers, strings, tuples, lists, and dictionaries. It also covers Python methods, operators, control flow statements, functions, modules, packages, and object-oriented programming concepts like classes.
Files and directories can be manipulated in Python using various functions. Files are opened, read from and written to using methods like open(), read(), write() and close(). Directories can be created, listed, changed and deleted using os module functions like mkdir(), listdir(), chdir() and rmdir(). File operations involve opening, performing read/write and closing the file.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending to add an item, inserting to add an item at a specific index, removing items, sorting lists, finding the length of a list, and accessing items by index.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data handling techniques.
The document provides an overview of common Python data structures and programming concepts including:
- Strings, variables, and concatenation for combining strings
- Lists for storing ordered sets of items that can be accessed by index or looped through
- Tuples for storing immutable sets of items similar to lists
- Dictionaries for storing connections between keys and values in non-ordered key-value pairs
- Common operations for each like appending, inserting, removing, sorting, and slicing items
It also covers conditional statements, functions, files, exceptions, classes and objects, user input/output, and while and for loops for iteration. The goal is to introduce fundamental Python programming concepts and data structures.
This document provides an overview of Python lists:
- Lists store a series of items in a particular order and allow you to access items using an index or loop through the items.
- You can add and remove items from lists, sort lists, loop through lists to print or modify items, and access items by index.
- Common list operations include appending items, inserting items, removing items, sorting lists, finding the length of a list, and accessing items by index. Lists provide a powerful way to organize and work with sets of data in Python.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading and writing file contents using methods like read(), readline(), readlines(), seeking to different positions, and closing files. Examples are provided to illustrate reading temperature data from one file and writing converted values to another file. The document also discusses creating, deleting and renaming files and folders using OS module functions.
The document discusses dictionaries in Python. It explains that a dictionary is a collection of unordered key-value pairs where keys must be unique. Keys can be strings, numbers, or tuples, while values can be any data type. Dictionaries allow accessing values using keys. Common dictionary operations include adding/updating items, checking if a key exists, getting values, and looping through keys and key-value pairs. The document also provides examples of using dictionaries to count word frequencies in a text file by parsing and removing punctuation.
This document discusses file handling in Python. It begins by explaining that files allow permanent storage of data, unlike standard input/output which is volatile. It then covers opening files in different modes, reading files line-by-line or as a whole, and modifying the file pointer position using seek(). Key points include opening files returns a file object, reading can be done line-by-line with for loops or using read()/readlines(), and seek() allows changing the file pointer location.
This document provides an overview of file handling in Python. It begins by outlining learning objectives related to understanding different file types, opening and closing files, and reading from and writing to files. It then discusses the need for data file handling to permanently store program data. Various file types are introduced, including text files, CSV files, and binary files. Methods for opening, reading from, writing to, and closing both text and binary files are described. The pickle module is explained for pickling and unpickling Python objects for storage in binary files. Finally, random access methods like tell() and seek() are briefly covered.
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyYannis
The doctoral thesis trajectory has been often characterized as a “long and windy road” or a journey to “Ithaka”, suggesting the promises and challenges of this journey of initiation to research. The doctoral candidates need to complete such journey (i) preserving and even enhancing their wellbeing, (ii) overcoming the many challenges through resilience, while keeping (iii) high standards of ethics and (iv) scientific rigor. This talk will provide a personal account of lessons learnt and recommendations from a senior researcher over his 30+ years of doctoral supervision and care for doctoral students. Specific attention will be paid on the special features of the (i) interdisciplinary doctoral research that involves Information and Communications Technologies (ICT) and other scientific traditions, and (ii) the challenges faced in the complex technological and research landscape dominated by Artificial Intelligence.
This document provides information about the Fifth edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
First Review PPT gfinal gyft ftu liu yrfut goSowndarya6
CyberShieldX provides end-to-end security solutions, including vulnerability assessment, penetration testing, and real-time threat detection for business websites. It ensures that organizations can identify and mitigate security risks before exploitation.
Unlike traditional security tools, CyberShieldX integrates AI models to automate vulnerability detection, minimize false positives, and enhance threat intelligence. This reduces manual effort and improves security accuracy.
Many small and medium businesses lack dedicated cybersecurity teams. CyberShieldX provides an easy-to-use platform with AI-powered insights to assist non-experts in securing their websites.
Traditional enterprise security solutions are often expensive. CyberShieldX, as a SaaS platform, offers cost-effective security solutions with flexible pricing for businesses of all sizes.
Businesses must comply with security regulations, and failure to do so can result in fines or data breaches. CyberShieldX helps organizations meet compliance requirements efficiently.
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...ijfcstjournal
One of the major challenges for software, nowadays, is software cost estimation. It refers to estimating the
cost of all activities including software development, design, supervision, maintenance and so on. Accurate
cost-estimation of software projects optimizes the internal and external processes, staff works, efforts and
the overheads to be coordinated with one another. In the management software projects, estimation must
be taken into account so that reduces costs, timing and possible risks to avoid project failure. In this paper,
a decision- support system using a combination of multi-layer artificial neural network and decision tree is
proposed to estimate the cost of software projects. In the model included into the proposed system,
normalizing factors, which is vital in evaluating efforts and costs estimation, is carried out using C4.5
decision tree. Moreover, testing and training factors are done by multi-layer artificial neural network and
the most optimal values are allocated to them. The experimental results and evaluations on Dataset
NASA60 show that the proposed system has less amount of the total average relative error compared with
COCOMO model.
Third Review PPT that consists of the project d etails like abstract.Sowndarya6
CyberShieldX is an AI-driven cybersecurity SaaS web application designed to provide automated security analysis and proactive threat mitigation for business websites. As cyber threats continue to evolve, traditional security tools like OpenVAS and Nessus require manual configurations and lack real-time automation. CyberShieldX addresses these limitations by integrating AI-powered vulnerability assessment, intrusion detection, and security maintenance services. Users can analyze their websites by simply submitting a URL, after which CyberShieldX conducts an in-depth vulnerability scan using advanced security tools such as OpenVAS, Nessus, and Metasploit. The system then generates a detailed report highlighting security risks, potential exploits, and recommended fixes. Premium users receive continuous security monitoring, automatic patching, and expert assistance to fortify their digital infrastructure against emerging threats. Built on a robust cloud infrastructure using AWS, Docker, and Kubernetes, CyberShieldX ensures scalability, high availability, and efficient security enforcement. Its AI-driven approach enhances detection accuracy, minimizes false positives, and provides real-time security insights. This project will cover the system's architecture, implementation, and its advantages over existing security solutions, demonstrating how CyberShieldX revolutionizes cybersecurity by offering businesses a smarter, automated, and proactive defense mechanism against ever-evolving cyber threats.
11th International Conference on Data Mining (DaMi 2025)kjim477n
Welcome To DAMI 2025
Submit Your Research Articles...!!!
11th International Conference on Data Mining (DaMi 2025)
July 26 ~ 27, 2025, London, United Kingdom
Submission Deadline : June 07, 2025
Paper Submission : https://csit2025.org/submission/index.php
Contact Us : Here's where you can reach us : [email protected] or [email protected]
For more details visit : Webpage : https://csit2025.org/dami/index
May 2025: Top 10 Read Articles Advanced Information Technologyijait
International journal of advanced Information technology (IJAIT) is a bi monthly open access peer-reviewed journal, will act as a major forum for the presentation of innovative ideas, approaches, developments, and research projects in the area advanced information technology applications and services. It will also serve to facilitate the exchange of information between researchers and industry professionals to discuss the latest issues and advancement in the area of advanced IT. Core areas of advanced IT and multi-disciplinary and its applications will be covered during the conferences.
chemistry investigatory project for class 12Susis10
Ad
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
1. 1
Online Workshop on ‘How to develop
Pythonic coding rather than Python
coding – Logic Perspective’
22.7.20 Day 2 session 2
Dr. S.Mohideen Badhusha
Sr.Professor/ CSE department
Alva’s Institute Engineering and
Technology
Mijar, Moodbidri, Mangalore
3. 3
To acquire knowledge of Dictionary and File
To comprehend the in-built functions and
operations in Dictionary and File
To practice the simple problems in Dictionary
and File
Objectives of the Day 2 session 2
4. 4
Dictionaries: A Mapping type
A dictionary in Python is a collection of items accessed by a specific
key rather than by index.
• Dictionaries store a mapping between a set of keys and a set of
values.
• Python dictionary is an unordered collection of items. While other
compound data types have only value as an element, a dictionary
has a key: value pair.
Dictionaries are optimized to retrieve values when the key is known.
– Keys can be any immutable type.
– Values can be any type
– A single dictionary can store values of different types
• You can define, modify, view, lookup, and delete the key-value pairs
in the dictionary.
5. 5
Creating and accessing
dictionaries
>>> d = {‘user’:‘bozo’, ‘pswd’:1234}
>>> d[‘user’]
‘bozo’
>>> d[‘pswd’]
1234
>>> d[‘bozo’]
Traceback (innermost last):
File ‘<interactive input>’ line 1, in ?
KeyError: bozo
6. 6
Updating Dictionaries
>>> d = {‘user’:‘bozo’, ‘pswd’:1234}
>>> d[‘user’] = ‘clown’
>>> d
{‘user’:‘clown’, ‘pswd’:1234}
• Keys must be unique.
• Assigning to an existing key replaces its value.
>>> d[‘id’] = 45
>>> d
{‘user’:‘clown’, ‘id’:45, ‘pswd’:1234}
• Dictionaries are unordered
– New entry might appear anywhere in the output.
• (Dictionaries work by hashing)
7. 7
Removing dictionary entries
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
>>> del d[‘user’] # Remove one.
>>> d
{‘p’:1234, ‘i’:34}
>>> d.clear() # Remove all.
>>> d
{}
8. 8
Useful Accessor Methods
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}
>>> d.keys() # List of keys.
[‘user’, ‘p’, ‘i’]
>>> d.values() # List of values.
[‘bozo’, 1234, 34]
>>> d.items() # List of item tuples.
[(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]
9. 9
How to create an empty dictionary?
Creating a dictionary is as simple as placing items inside curly
braces {} separated by comma.
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
#list of tuples can be changed as dict using dict()
l=[(1,'apple'), (2,'ball')
my_dict = dict(l)
print(my_dict)
#o/p : {1:'apple', 2:'ball'}
10. 10
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
# Output: Jack
print(my_dict.get('age'))
# Output: 26
How to change or add elements in a dictionary?
my_dict = {'name':'Jack', 'age': 26}
my_dict['age'] = 27
# update value of key age
print(my_dict)
#Output: {'age': 27, 'name': 'Jack'}
# add an item
my_dict['address'] = 'Downtown'
print(my_dict)
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
11. 11
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item of the key 4
print(squares.pop(4))
# Output: 16
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
# remove last item
print(squares.popitem())
# Output: (5, 25)
print(squares)
# Output: {1: 1, 2: 4, 3: 9}
# delete a particular item
del squares[2]
12. 12
print(squares)
# Output: {1: 1, 3: 9}
# remove all items
squares.clear()
print(squares)
# Output: {}
# delete the dictionary itself
del squares
# Throws Error
print(squares)
13. 13
#Initializing the values in dict
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
squares = {x: x*x for x in range(6)} # using list comprehension
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
This code is equivalent to
squares = {}
for x in range(6):
squares[x] = x*x
odd_squares = {x: x*x for x in range(11) if x%2 == 1}
print(odd_squares)
# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
14. 14
Iterating Through a Dictionary
Using a for loop we can iterate though each key
in a dictionary.
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
15. 15
Dictionary comprehension
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Check for values greater than 2
d = {k:v for (k,v) in dict1.items() if v>2}
print(d)
# output
{'e': 5, 'c': 3, 'd': 4}
# multiple conditions
d1 = {k:v for (k,v) in dict1.items() if v>2 if v%2 == 0}
print(d1)
#output
{'d': 4}
16. 16
Files in Python
Open ( ) Function
In order to open a file for writing or use in Python, you
must rely on the built-in open () function.
As explained above, open ( ) will return a file object, so it
is most commonly used with two arguments. Syntax is
file_object = open(“filename”, “mode”) where
file_object is the variable to add the file object.
Mode
Including a mode argument is optional because a
default value of ‘r’ will be assumed if it is omitted. The
‘r’ value stands for read mode, which is just one of
many.
17. 17
The modes are:
‘r’ – Read mode which is used when the file is only
being read
‘w’ – Write mode which is used to edit and write new
information to the file (any existing files with the same
name will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data
to the end of the file; that is new information is
automatically appended to the end
18. 18
The modes are:
‘r+’ – Opens a file for both reading and writing.
The file pointer placed at the beginning of the file.
‘w+’ – Opens a file for both writing and reading.
Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading
and writing.
‘a+’ – Opens a file for both appending and reading.
The file 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.
19. 19
Create a Text file
#(filewrite and read.py)
fo = open("foo2.txt", "w")
print ("Name of the file: ", fo.name)
fo.write("Python is a great language Yeah its great!")
# Close opened file
fo.close()
fo = open("foo2.txt", "r")
str1=fo.readline()
print ("Read String is :",str1)
# Close opend file
fo.close()
20. 20
o/p
Name of the file: foo2.txt
Read String is : Python is a wonderful language
Yeah its great!
21. 21
# filemultiread.py
fo = open("foo2.txt", "a")
fo.write("Python is very wonderful language!")
# Close opened file
fo.close()
print ("Entire file is :")
fo = open("foo2.txt", "r")
for line in fo:
print(line)
# Close opend file
fo.close()
22. 22
’’’file reading the file line by line by opening and
creating object at a stretch’’’
# Display line by line information from a file
filename=input("Enter file name: ")
with open (filename,'r') as f:
for line in f:
print(line)
# Display word by word information from a file
filename=input("Enter file name: ")
with open (filename,'r') as f:
for line in f:
l=line.split()
for word in l:
print(word)
23. 23
# Display only first line using readline() from a file
filename=input("Enter file name: ")
with open (filename,'r') as f:
l=f.readline() # stores 1st
line from the file
print(l)
# Display line by line info using readlines() from a file
filename=input("Enter file name: ")
with open (filename,'r') as f:
l=f.readlines() # stores list of lines in l
for i in l:
print(i)
24. 24
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(4)
print ("Read String is : ", str)
fo.write(" I am new sentence")
# Check current position
position = fo.tell()
print ("Current file position : ", position)
# Reposition pointer at the beginning once again
position = fo.seek(0, 0)
str = fo.read(30)
print ("Again read String is : ", str)
# Close opened file
fo.close()
25. 25
Read String is : I am
Current file position : 52
Again read String is : I am new sentenceI am new sent
26. 26
Concluding Tips
dictionary- mutable (changeable) but key –
immutable ( unchangeable)
Dictionaries store a mapping between a set of keys and a
set of values.
A dictionary has a key: value pair.
A dictionary can have mixed data types
File is a permanent data structure. The data stored in file is
consistent even after the program execution where as other
data structures such as list, tuple,dictionary all are
temporary data structure