The document provides information about file handling in Python. It discusses the basic operations on files like opening, reading, writing and closing files. It explains text files and binary files, different file access modes, and methods to read and write data from/to files like readline(), readlines(), read(), write() and writelines(). It also covers random access methods like seek() and tell() as well as pickling and unpickling using the pickle module. Finally, it highlights the differences between text and binary files.
The document discusses data file handling in Python. It covers the basics of opening, reading from, and writing to both text and binary files.
The key points covered include: opening and closing files, different file access modes, reading methods like readline(), readlines(), and read(), writing methods like write() and writelines(), random access methods like seek() and tell(), pickling and unpickling using the pickle module, and the differences between text and binary files.
This document provides an overview of file handling in Python. It discusses different file types like text files, binary files, and CSV files. It explains how to open, read, write, close, and delete files using functions like open(), read(), write(), close(), and os.remove(). It also covers reading and writing specific parts of a file using readline(), readlines(), seek(), and tell(). The document demonstrates how to handle binary files using pickle for serialization and deserialization. Finally, it shows how the os module can be used for file operations and how the csv module facilitates reading and writing CSV files.
Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
Computer program works with files. This is because files help in storing information permanently. A file is a bunch of bytes stored on some secondary storage devices.
The document discusses file handling in Python. It covers opening and closing files, reading and writing to files, and different file access modes. It describes opening files using the open() function and closing files using the close() method. It explains how to read from files using methods like read(), readline(), and readlines(). It also covers writing to files using write(), writelines(), and seeking to specific positions using seek() and tell(). The document provides examples of reading, writing, and manipulating text files in Python.
This document discusses file handling in Python. File handling allows Python programs to read from and write data to disk files for permanent storage. The open() function is used to open a file and return a file object, which has methods like read(), write(), close() to interact with the file. Files can be opened in different modes like read, write, append. The read() method reads from the file while write() writes to it. Files must be closed using close() after processing to flush buffers and close the file properly.
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.
This document discusses files, modules, packages and exceptions in Python. It covers reading and writing to text files, opening and closing files, different file access modes, file positions, command line arguments, and common exceptions in Python like syntax errors and exceptions raised during execution. Key topics include using open(), read(), write(), close() functions to perform file operations, os and os.path modules for file and path operations, and sys.argv to access command line arguments in a Python program. Examples are provided for reading, writing, appending files and handling exceptions.
This document discusses Python's built-in functions and methods for performing input/output operations (I/O) and manipulating files and directories. It covers printing to the screen, reading keyboard input, opening and closing files, reading and writing files, file positions, renaming and deleting files, and creating, removing, and changing directories.
The document discusses Python's built-in functions and methods for reading, writing, and manipulating files and directories. It explains how to open and close files, read and write file contents, check file positions, rename and delete files, create and remove directories, and get the current working directory using functions like open(), close(), read(), write(), tell(), seek(), os.rename(), os.remove(), os.mkdir(), os.chdir(), and os.getcwd(). It also covers the different modes for opening files and lists attributes of file objects.
Files in Python can be used to permanently store data on disk. There are two main types - text files and binary files. Text files can be opened in a text editor while binary files require specific software. To handle files in Python, they must be opened, have operations performed, and then closed. There are different modes for opening files - read, write, append. The open() function returns a file object that can be used to read, write, close the file using methods like read(), write(), close(). Care must be taken when writing to ensure old data isn't overwritten.
FILE HANDLING in python to understand basic operations.ssuser00ad4e
The document discusses file handling in Python. It describes how to open, read from, write to, and close files. The key points are:
- Files can be opened in read, write, append modes using the open() function, which returns a file object.
- Reading file data uses functions like read(), readline(), and readlines(). Write uses write() and writelines().
- Files must be closed using the close() method on the file object after reading or writing to release system resources.
- Text files store data as characters while binary files store exact data types. Mode 'w' overwrites, 'a' appends without overwriting existing data.
This document discusses file operations in Python. It defines what a file is and explains that files are used to permanently store data on storage devices like hard disks. It describes the basic file operations of opening, reading, writing, and closing files. It also discusses text and binary file types and how to rename, delete, and get attribute information about files in Python.
The document discusses file handling in Python. It explains that files are used to permanently store data on disk. There are two main types of files - text files and binary files. Text files can be opened in a text editor while binary files require specific software. The key steps for file operations in Python are to open the file, perform read/write operations, and close the file. Methods like open(), read(), write(), close() are used to perform various file operations. The document also discusses reading, writing, appending and binary file operations in Python.
Data file handling in python reading & writing methodskeeeerty
This document discusses various methods for reading and writing files in Python. It describes readline(), readlines(), and read() methods for reading files line-by-line or in full. It also covers write() and writelines() methods for writing strings or lists to files, and discusses opening files in different modes and manipulating the file pointer position. Standard input, output, and error streams are also briefly explained.
Data file handling in python reading & writing methodsKeerty Smile
This document discusses various methods for reading and writing files in Python. It describes readline(), readlines(), and read() methods for reading files line-by-line or in full. It also covers write() and writelines() methods for writing strings or lists to files, and discusses opening files in different modes and manipulating the file pointer position. Standard input, output, and error streams are also briefly explained.
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.
מכונות CNC קידוח אנכיות הן הבחירה הנכונה והטובה ביותר לקידוח ארונות וארגזים לייצור רהיטים. החלק נוסע לאורך ציר ה-x באמצעות ציר דיגיטלי מדויק, ותפוס ע"י צבת מכנית, כך שאין צורך לבצע setup (התאמות) לגדלים שונים של חלקים.
Textbook Solutions refer https://pythonxiisolutions.blogspot.com/
Practical's Solutions refer https://prippython12.blogspot.com/
Computer program works with files. This is because files help in storing information permanently. A file is a bunch of bytes stored on some secondary storage devices.
The document discusses file handling in Python. It covers opening and closing files, reading and writing to files, and different file access modes. It describes opening files using the open() function and closing files using the close() method. It explains how to read from files using methods like read(), readline(), and readlines(). It also covers writing to files using write(), writelines(), and seeking to specific positions using seek() and tell(). The document provides examples of reading, writing, and manipulating text files in Python.
This document discusses file handling in Python. File handling allows Python programs to read from and write data to disk files for permanent storage. The open() function is used to open a file and return a file object, which has methods like read(), write(), close() to interact with the file. Files can be opened in different modes like read, write, append. The read() method reads from the file while write() writes to it. Files must be closed using close() after processing to flush buffers and close the file properly.
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.
This document discusses files, modules, packages and exceptions in Python. It covers reading and writing to text files, opening and closing files, different file access modes, file positions, command line arguments, and common exceptions in Python like syntax errors and exceptions raised during execution. Key topics include using open(), read(), write(), close() functions to perform file operations, os and os.path modules for file and path operations, and sys.argv to access command line arguments in a Python program. Examples are provided for reading, writing, appending files and handling exceptions.
This document discusses Python's built-in functions and methods for performing input/output operations (I/O) and manipulating files and directories. It covers printing to the screen, reading keyboard input, opening and closing files, reading and writing files, file positions, renaming and deleting files, and creating, removing, and changing directories.
The document discusses Python's built-in functions and methods for reading, writing, and manipulating files and directories. It explains how to open and close files, read and write file contents, check file positions, rename and delete files, create and remove directories, and get the current working directory using functions like open(), close(), read(), write(), tell(), seek(), os.rename(), os.remove(), os.mkdir(), os.chdir(), and os.getcwd(). It also covers the different modes for opening files and lists attributes of file objects.
Files in Python can be used to permanently store data on disk. There are two main types - text files and binary files. Text files can be opened in a text editor while binary files require specific software. To handle files in Python, they must be opened, have operations performed, and then closed. There are different modes for opening files - read, write, append. The open() function returns a file object that can be used to read, write, close the file using methods like read(), write(), close(). Care must be taken when writing to ensure old data isn't overwritten.
FILE HANDLING in python to understand basic operations.ssuser00ad4e
The document discusses file handling in Python. It describes how to open, read from, write to, and close files. The key points are:
- Files can be opened in read, write, append modes using the open() function, which returns a file object.
- Reading file data uses functions like read(), readline(), and readlines(). Write uses write() and writelines().
- Files must be closed using the close() method on the file object after reading or writing to release system resources.
- Text files store data as characters while binary files store exact data types. Mode 'w' overwrites, 'a' appends without overwriting existing data.
This document discusses file operations in Python. It defines what a file is and explains that files are used to permanently store data on storage devices like hard disks. It describes the basic file operations of opening, reading, writing, and closing files. It also discusses text and binary file types and how to rename, delete, and get attribute information about files in Python.
The document discusses file handling in Python. It explains that files are used to permanently store data on disk. There are two main types of files - text files and binary files. Text files can be opened in a text editor while binary files require specific software. The key steps for file operations in Python are to open the file, perform read/write operations, and close the file. Methods like open(), read(), write(), close() are used to perform various file operations. The document also discusses reading, writing, appending and binary file operations in Python.
Data file handling in python reading & writing methodskeeeerty
This document discusses various methods for reading and writing files in Python. It describes readline(), readlines(), and read() methods for reading files line-by-line or in full. It also covers write() and writelines() methods for writing strings or lists to files, and discusses opening files in different modes and manipulating the file pointer position. Standard input, output, and error streams are also briefly explained.
Data file handling in python reading & writing methodsKeerty Smile
This document discusses various methods for reading and writing files in Python. It describes readline(), readlines(), and read() methods for reading files line-by-line or in full. It also covers write() and writelines() methods for writing strings or lists to files, and discusses opening files in different modes and manipulating the file pointer position. Standard input, output, and error streams are also briefly explained.
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.
מכונות CNC קידוח אנכיות הן הבחירה הנכונה והטובה ביותר לקידוח ארונות וארגזים לייצור רהיטים. החלק נוסע לאורך ציר ה-x באמצעות ציר דיגיטלי מדויק, ותפוס ע"י צבת מכנית, כך שאין צורך לבצע setup (התאמות) לגדלים שונים של חלקים.
Domino IQ – What to Expect, First Steps and Use Casespanagenda
Webinar Recording: https://www.panagenda.com/webinars/domino-iq-what-to-expect-first-steps-and-use-cases/
HCL Domino iQ Server – From Ideas Portal to implemented Feature. Discover what it is, what it isn’t, and explore the opportunities and challenges it presents.
Key Takeaways
- What are Large Language Models (LLMs) and how do they relate to Domino iQ
- Essential prerequisites for deploying Domino iQ Server
- Step-by-step instructions on setting up your Domino iQ Server
- Share and discuss thoughts and ideas to maximize the potential of Domino iQ
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Safe Software
Jacobs has developed a 3D utility solids modelling workflow to improve the integration of utility data into 3D Building Information Modeling (BIM) environments. This workflow, a collaborative effort between the New Zealand Geospatial Team and the Australian Data Capture Team, employs FME to convert 2D utility data into detailed 3D representations, supporting enhanced spatial analysis and clash detection.
To enable the automation of this process, Jacobs has also developed a survey data standard that standardizes the capture of existing utilities. This standard ensures consistency in data collection, forming the foundation for the subsequent automated validation and modelling steps. The workflow begins with the acquisition of utility survey data, including attributes such as location, depth, diameter, and material of utility assets like pipes and manholes. This data is validated through a custom-built tool that ensures completeness and logical consistency, including checks for proper connectivity between network components. Following validation, the data is processed using an automated modelling tool to generate 3D solids from 2D geometric representations. These solids are then integrated into BIM models to facilitate compatibility with 3D workflows and enable detailed spatial analyses.
The workflow contributes to improved spatial understanding by visualizing the relationships between utilities and other infrastructure elements. The automation of validation and modeling processes ensures consistent and accurate outputs, minimizing errors and increasing workflow efficiency.
This methodology highlights the application of FME in addressing challenges associated with geospatial data transformation and demonstrates its utility in enhancing data integration within BIM frameworks. By enabling accurate 3D representation of utility networks, the workflow supports improved design collaboration and decision-making in complex infrastructure projects
Trends Artificial Intelligence - Mary MeekerClive Dickens
Mary Meeker’s 2024 AI report highlights a seismic shift in productivity, creativity, and business value driven by generative AI. She charts the rapid adoption of tools like ChatGPT and Midjourney, likening today’s moment to the dawn of the internet. The report emphasizes AI’s impact on knowledge work, software development, and personalized services—while also cautioning about data quality, ethical use, and the human-AI partnership. In short, Meeker sees AI as a transformative force accelerating innovation and redefining how we live and work.
מכונת קנטים המתאימה לנגריות קטנות או גדולות (כמכונת גיבוי).
מדביקה קנטים מגליל או פסים, עד עובי קנט – 3 מ"מ ועובי חומר עד 40 מ"מ. בקר ממוחשב המתריע על תקלות, ומנועים מאסיביים תעשייתיים כמו במכונות הגדולות.
Floods in Valencia: Two FME-Powered Stories of Data ResilienceSafe Software
In October 2024, the Spanish region of Valencia faced severe flooding that underscored the critical need for accessible and actionable data. This presentation will explore two innovative use cases where FME facilitated data integration and availability during the crisis. The first case demonstrates how FME was used to process and convert satellite imagery and other geospatial data into formats tailored for rapid analysis by emergency teams. The second case delves into making human mobility data—collected from mobile phone signals—accessible as source-destination matrices, offering key insights into population movements during and after the flooding. These stories highlight how FME's powerful capabilities can bridge the gap between raw data and decision-making, fostering resilience and preparedness in the face of natural disasters. Attendees will gain practical insights into how FME can support crisis management and urban planning in a changing climate.
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Anish Kumar
Presented by: Anish Kumar
LinkedIn: https://www.linkedin.com/in/anishkumar/
This lightning talk dives into real-world GenAI projects that scaled from prototype to production using Databricks’ fully managed tools. Facing cost and time constraints, we leveraged four key Databricks features—Workflows, Model Serving, Serverless Compute, and Notebooks—to build an AI inference pipeline processing millions of documents (text and audiobooks).
This approach enables rapid experimentation, easy tuning of GenAI prompts and compute settings, seamless data iteration and efficient quality testing—allowing Data Scientists and Engineers to collaborate effectively. Learn how to design modular, parameterized notebooks that run concurrently, manage dependencies and accelerate AI-driven insights.
Whether you're optimizing AI inference, automating complex data workflows or architecting next-gen serverless AI systems, this session delivers actionable strategies to maximize performance while keeping costs low.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2025/06/state-space-models-vs-transformers-for-ultra-low-power-edge-ai-a-presentation-from-brainchip/
Tony Lewis, Chief Technology Officer at BrainChip, presents the “State-space Models vs. Transformers for Ultra-low-power Edge AI” tutorial at the May 2025 Embedded Vision Summit.
At the embedded edge, choices of language model architectures have profound implications on the ability to meet demanding performance, latency and energy efficiency requirements. In this presentation, Lewis contrasts state-space models (SSMs) with transformers for use in this constrained regime. While transformers rely on a read-write key-value cache, SSMs can be constructed as read-only architectures, enabling the use of novel memory types and reducing power consumption. Furthermore, SSMs require significantly fewer multiply-accumulate units—drastically reducing compute energy and chip area.
New techniques enable distillation-based migration from transformer models such as Llama to SSMs without major performance loss. In latency-sensitive applications, techniques such as precomputing input sequences allow SSMs to achieve sub-100 ms time-to-first-token, enabling real-time interactivity. Lewis presents a detailed side-by-side comparison of these architectures, outlining their trade-offs and opportunities at the extreme edge.
Artificial Intelligence in the Nonprofit Boardroom.pdfOnBoard
OnBoard recently partnered with Microsoft Tech for Social Impact on the AI in the Nonprofit Boardroom Survey, an initiative designed to uncover the current and future role of artificial intelligence in nonprofit governance.
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfällepanagenda
Webinar Recording: https://www.panagenda.com/webinars/domino-iq-was-sie-erwartet-erste-schritte-und-anwendungsfalle/
HCL Domino iQ Server – Vom Ideenportal zur implementierten Funktion. Entdecken Sie, was es ist, was es nicht ist, und erkunden Sie die Chancen und Herausforderungen, die es bietet.
Wichtige Erkenntnisse
- Was sind Large Language Models (LLMs) und wie stehen sie im Zusammenhang mit Domino iQ
- Wesentliche Voraussetzungen für die Bereitstellung des Domino iQ Servers
- Schritt-für-Schritt-Anleitung zur Einrichtung Ihres Domino iQ Servers
- Teilen und diskutieren Sie Gedanken und Ideen, um das Potenzial von Domino iQ zu maximieren
Your startup on AWS - How to architect and maintain a Lean and Mean account J...angelo60207
Prevent infrastructure costs from becoming a significant line item on your startup’s budget! Serial entrepreneur and software architect Angelo Mandato will share his experience with AWS Activate (startup credits from AWS) and knowledge on how to architect a lean and mean AWS account ideal for budget minded and bootstrapped startups. In this session you will learn how to manage a production ready AWS account capable of scaling as your startup grows for less than $100/month before credits. We will discuss AWS Budgets, Cost Explorer, architect priorities, and the importance of having flexible, optimized Infrastructure as Code. We will wrap everything up discussing opportunities where to save with AWS services such as S3, EC2, Load Balancers, Lambda Functions, RDS, and many others.
3. LEARNING OUTCOMES
After going through the chapter, student will
be able to:
Understand the importance of data file
for permanent storage of data.
Understand how standard Input/Output
function work.
Distinguish between text and binary file
Open and close a file ( text and binary)
Read and write data in file
Write programs that manipulate data
file(s
4. INTRODUCTION – DATA FILES
A file (i.e. data file) is a named place on the
disk where a sequence of related data is stored.
In python files are simply stream of data,
so the structure of data is not stored in the file,
along with data.
6. Basic operations performed on a data file are:
1. Naming a file
2. Opening a file
3. Reading data from the file
4. Writing data in the file
5. Closing a file
BASIC OPERATIONS ON FILE
8. Using these basic operations, we can process
file in many ways, such as
1. CREATING A FILE
2. TRAVERSING A FILE FOR DISPLAYING THE DATA ON
SCREEN
3. APPENDING DATA IN FILE
4. INSERTING DATA IN FILE
Contd.. next
FILE PROCESSING
9. INTRODUCTION – DATA FILES
6. CREATE A COPY OF FILE
7. UPDATING DATA IN THE FILE …
etc
5. DELETING DATA FROM FILE
11. TYPES OF FILES
Python allow us to create and manage two
types of file
1. TEXT FILE
2. BINARY FILE
12. What is Text File?
A text file is usually considered as
sequence of lines. Line is a sequence of
characters (ASCII or UNICODE), stored on
permanent storage media. The default
character coding in python is ASCII each line
is terminated by a special character, known
as End of Line (EOL). At the lowest level,
text file will be collection of bytes. Text files
are stored in human readable form and they
can also be created using any text editor.
1. TEXT FILE
13. What is Binary File?
A binary file contains arbitrary binary data
i.e. numbers stored in the file, can be used for
numerical operation(s). So when we work on
binary file, we have to interpret the raw bit
pattern(s) read from the file into correct type
of data in our program. In the case of binary
file it is extremely important that we interpret
the correct data type while reading the file.
Python provides special module(s) for encoding
and decoding of data for binary file.
2. BINARY FILE
15. OPENING AND CLOSING FILES
To handle data files in python, we
need to have a file object. Object can be
created by using open() function or file()
function.
To work on file, first thing we do is open it.
This is done by using built in function open().
Syntax of open() function is
file_object = open(filename [, access_mode]
[,buffering])
16. OPENING AND CLOSING FILES
open() requires three arguments to work,
first one ( filename ) is the name of the file on
secondary storage media, which can be string
constant or a variable. The name can include the
description of path, in case, the file does not
reside in the same folder / directory in which we
are working
The second parameter (access_mode)
describes how file will be used throughout the
program. This is an optional parameter and the
default access_mode is reading.
17. OPENING AND CLOSING FILES
The third parameter (buffering) is for
specifying how much is read from the file in one
read.
Finally, The function will return an object of
file type using which we will manipulate the
file, in our program.
When we work with file(s), a buffer (area in
memory where data is temporarily stored
before being written to file), is automatically
associated with file when we open the file.
18. OPENING AND CLOSING FILES
While writing the content in the file, first it
goes to buffer and once the buffer is full, data
is written to the file. Also when file is closed,
any unsaved data is transferred to file. flush()
function is used to force transfer of data from
buffer to file
20. FILE ACCESS MODES
MODE File Opens in
r Text File Read Mode
rb Binary File Read Mode
These are the default modes. The file
pointer is placed at the beginning for
reading purpose, when we open a file in
this mode.
21. FILE ACCESS MODES
MODE File Opens in
r+ Text File Read & Write Mode
rb+ Binary File Read Write Mode
w Text file write mode
wb Text and Binary File Write Mode
w+ Text File Read and Write Mode
wb+ Text and Binary File Read and Write
Mode
a Appends text file at the end of file, if
file does not exists it creates the file.
22. FILE ACCESS MODES
MODE File Opens in
ab Appends both text and binary files at
the end of file, if file does not exists it
creates the file.
a+ Text file appending and reading.
ab+ Text and Binary file for appending and
reading.
23. FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“notes.txt”, ‘r’)
This is the default mode for a
file.
notes.txt is a text file and is
opened in read mode only.
24. FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“notes.txt”, ‘r+’)
notes.txt is a text file and is
opened in read and write mode.
25. FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“tests.dat ”, ‘rb’)
tests.dat is a binary file and
is opened in read only mode.
26. FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“tests.dat”, ‘rb+’)
tests.dat is binary file and is
opened in both modes that is
reading and writing.
27. FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“tests.dat”, ‘ab+’)
tests.dat is binary file and is
opened in both modes that is
reading and appending.
29. close FUNCTION
fileobject. close() will be used to close
the file object, once we have finished
working on it. The method will free up all
the system resources used by the file, this
means that once file is closed, we will not
be able to use the file object any more.
For example:
f.close()
32. FILE READING METHODS
Followings are the methods to read a
data from the file.
1. readline() METHOD
2. readlines() METHOD
3. read() METHOD
33. readline() METHOD
readline() will return a line read, as a
string from the file. First call to function
will return first line, second call next line
and so on.
It's syntax is,
fileobject.readline()
37. readlines() METHOD
readlines()can be used to read the
entire content of the file. You need to be
careful while using it w.r.t. size of
memory required before using the
function. The method will return a list of
strings, each separated by n. An example
of reading entire data of file in list is:
It's syntax is,
fileobject.readlines()
as it returns a list, which can then be
used for manipulation.
44. read(size) METHOD
read() can be used to read specific
size string from file. This function also
returns a string read from the file.
Syntax of read() function is:
fileobject.read([size])
For Example:
f.read(1) will read single byte
or character from a file.
50. 1. write () METHOD
For sending data in file, i.e. to create
/ write in the file, write() and
writelines() methods can be used.
write() method takes a string ( as
parameter ) and writes it in the file.
For storing data with end of line
character, you will have to add n
character to end of the string
51. 1. write () METHOD EXAMPLE
Use ‘a’ in open function to append
or add the information to the file. ‘a+’
to add as well as read the file.
52. 1. write () METHOD EXAMPLE
if you execute the program n times, the
file is opened in w mode meaning it deletes
content of file and writes fresh every time
you run.
53. 1. write () METHOD EXAMPLE O/P
if you execute the program n times, the
file is opened in w mode meaning it deletes
content of file and writes fresh every time
you run.
54. 1. write () METHOD EXAMPLE 2
now content of test1.txt is changed
because the file is opened in w mode and
this mode deletes all content and writes
fresh if file exists. n write to next line. If
not used it writes on the same line.
55. 1. write () METHOD EXAMPLE 2
So test1.txt is already exists in
harddisk and it deletes all content and
writes fresh. If file not found it creates
new file.
56. 1. write () METHOD EXAMPLE 2
So test1.txt is already exists in
harddisk and it deletes all content and
writes fresh. If file not found it creates
new file.
57. 2. writelines() METHOD
For writing a string at a time, we use
write() method, it can't be used for
writing a list, tuple etc. into a file.
Sequence data type can be written
using writelines() method in the file. It's
not that, we can't write a string using
writelines() method.
It's syntax is:
fileobject.writelines(seq)
58. 2. writelines() METHOD
So, whenever we have to write a
sequence of string / data type, we will
use writelines(), instead of write().
Example:
f = open('test2.txt','w')
str = 'hello world.n this is my first file
handling program.n I am using python
language"
f.writelines(str)
f.close()
60. RANDOM ACCESS METHODS
All reading and writing functions
discussed till now, work sequentially in
the file. To access the contents of file
randomly –following methods are use.
seek method
tell method
61. seek()method can be used to position
the file object at particular place in the
file.
It's syntax is :
fileobject.seek(offset [, from_what])
here offset is used to calculate the
position of fileobject in the file in bytes.
Offset is added to from_what (reference
point) to get the position. Following is the
list of from_what values:
seek method
62. Value reference point
0 beginning of the file
1 current position of file
2 end of file
default value of from_what is 0, i.e.
beginning of the file.
seek method
65. Reading according to size
In the input function if you specify the
number of bytes that many number of
bytes can be fetched and assigned to an
identifier.
66. Reading according to size
f.read(1) will read single byte/
character starting from byte number 8.
hence byte number 8 is P so one
character/byte is fetched and assigned to
f_data identifier.
67. Reading according to size
f.read(2) - will read 2 chars/bytes
f.read(4) - will read 4 chars/bytes
and so on..
68. tell() method returns an integer giving
the current position of object in the file.
The integer returned specifies the
number of bytes from the beginning of
the file till the current position of file
object.
It's syntax is
fileobject.tell()
tell method
81. PICKELING AND UNPICKLING
USING PICKEL MODULE
Use the python module pickle for
structured data such as list or directory to a
file.
PICKLING refers to the process of
converting the structure to a byte stream
before writing to a file.
while reading the contents of the file, a
reverse process called UNPICKLING is used
to convert the byte stream back to the
original structure.
82. PICKELING AND UNPICKLING
USING PICKEL MODULE
First we need to import the module, It
provides two main methods for the
purpose:-
1) dump() method
2) load() method
83. pickle.dump() Method
Use pickle.dump() method to write
the object in file which is opened in
binary access mode.
Syntax of dump method is:
dump(object,fileobject)
93. DIFFERENCE BETWEEN TEXT FILESAND BINARY
FILES
Text Files Binary Files
1. Text Files are
sequential files
1. A Binary file
contain arbitrary
binary data
2. Text files only
stores texts
2 Binary Files are
used to store binary
data such as image,
video, audio, text
3. There is a
delimiter EOL (End
of Line i.e n)
3. There is no
delimiter
94. DIFFERENCE BETWEEN TEXT FILESAND BINARY
FILES
Text Files Binary Files
4. Due to delimiter
text files takes more
time to process. while
reading or writing
operations are
performed on file.
4. No presence of
delimiter makes files
to process fast while
reading or writing
operations are
performed on file.
5. Text files easy to
understand because
these files are in
human readable form
5. Binary files are
difficult to
understand.
95. DIFFERENCE BETWEEN TEXT FILESAND BINARY
FILES
Text Files Binary Files
6. Text files are
having extension
.txt
6. Binary files are
having .dat
extension
7. Programming on
text files are very
easy.
7. Programming on
binary files are
difficult.
96. DIFFERENCE BETWEEN TEXT FILES
AND BINARY FILES
TEXT FILE BINARY FILE
1. Bits represent
character.
1. Bits represent a
custom data.
2. Less prone to get
corrupt as changes
reflect as soon as the
file is opened and
can easily be undone
2. Can easily get
corrupted, even a
single bit change
may corrupt the file.
97. DIFFERENCE BETWEEN TEXT FILES
AND BINARY FILES
TEXT FILE BINARY FILE
3. Can store only
plain text in a file.
3. Can store
different types of
data (image, audio,
text) in a single file.
4. Widely used file
format and can be
opened using any
simple text editor.
4. Developed
especially for an
application and may
not be understood by
other applications.
98. DIFFERENCE BETWEEN TEXT FILES
AND BINARY FILES
TEXT FILE BINARY FILE
5. Mostly .txt and
.rtf are used as
extensions to text
files.
5. Can have any
application defined
extension.
100. PYTHON FILE OBJECT ATTRIBUTES
File attributes give information about
the file and file state.
Attribute Function
name Returns the name of the file
closed
Returns true if file is closed.
False otherwise.
mode The mode in which file is open.
softspace
Returns a Boolean that indicates
whether a space character
needs to be printed before
another value when using the
print statement.
102. OTHER METHODS OF FILEOBJECT
Method Function
readable()
Returns True/False whether file is
readable
writable()
Returns True/False whether file is
writable
fileno()
Return the Integer descriptor used
by Python to request I/O operations
from Operating System
flush()
Clears the internal buffer for the
file.
103. OTHER METHODS OF FILEOBJECT
Method Function
isatty()
Returns True if file is connected to
a Tele-TYpewriter (TTY) device or
something similar.
truncate([size)
Truncate the file, up to specified
bytes.
next(iterator,[d
efault])
Iterate over a file when file is used
as an iterator, stops iteration when
reaches end-of-file (EOF) for
reading.
105. HANDLING FILES THROUGH
OS MODULE
The os module of Python allows you to
perform Operating System dependent
operations such as making a folder, listing
contents of a folder, know about a
process, end a process etc..
Let's see some useful os module
methods that can help you to handle files
and folders in your program.
107. ABSOLUTE PATH
Absolute path of file is file location,
where in it starts from the top most
directory
ABSOLUTE PATH
108. RELATIVE PATH
Relative Path of file is file location,
where in it starts from the current
working directory
Myfoldermyfile.txt
RELATIVE PATH
109. HANDLING FILES THROUGH
OS MODULE
Method Function
os.makedirs() Create a new folder
os.listdir() List the contents of a folder
os.getcwd()
Show current working
directory
os.path.getsize()
show file size in bytes of file
passed
in parameter
os.path.isfile() Is passed parameter a file
os.path.isdir() Is passed parameter a folder
os.chdir Change directory/folder
110. HANDLING FILES THROUGH
OS MODULE
Method Function
os.rename(current,new
)
Rename a file
os.remove(file_name) Delete a file
112. PROGRAMS
1. Write a function to create a text file
containing following data
Neither apple nor pine are in pineapple.
Boxing rings are square.
Writers write, but fingers don't fing.
Overlook and oversee are opposites. A
house can burn up as it
burns down. An alarm goes off by going on.
113. PROGRAMS
2. Read back the entire file content using
read() or readlines () and display on
screen.
3. Append more text of your choice in the
file and display the content of file with line
numbers
prefixed to line.
4. Display last line of file.
Contd..
114. PROGRAMS
5. Display first line from 10th character
onwards
6. Read and display a line from the file. Ask
user to provide the line number to be read.
115. PROGRAMS
7. A text file named MATTER.TXT contains
some text, which needs to be displayed
such that every next character is
separated by a symbol ‘#’.
8. Write a statement in Python to open a
text file STORY.TXT so that new
contents can be added at the end of it.
116. PROGRAMS
9. Write a method in Python to read lines
from a text file INDIA.TXT, to find and
display the occurrence of the word
‘‘India’’.
For example :
If the content of the file is
‘‘India is the fastest growing economy.
India is looking for more investments around the
globe.
The whole world is looking at India as a great
market.
Most of the Indians can foresee the heights that
India is
capable of reaching.’’
The output should be 4.
117. PROGRAMS
10. Write a function to count total number of
spaces, lines and characters in a given line
of text
118. PROGRAMS
11. Write a function to count total number of
digits in a given line of text
119. PROGRAMS
12. Write a function to copy the content of
notes.txt to sub.txt
NOTES.txt FILE
135. PROGRAMS
16. Write a function COUNT_DO( ) in
Python to count the presence of a word
‘do’ in a text file “MEMO.TXT”.
Example :
If the content of the file “MEMO.TXT” is as
follows:
I will do it, if you request me to do it.
It would have been done much earlier.
The function COUNT_DO( ) will display the
following message:
Count of -do- in flie:
136. PROGRAMS
17. Write a function in Python to count
the no. of “Me” or “My” words present in a
text file “DIARY.TXT”.
If the file “DIARY.TXT” content is as follows
:
My first book was Me and My family. It gave
me chance to be known to the world.
The output of the function should be Count
of
Me/ My in file :
137. PROGRAMS
18. Write a function in Python to count and
display the number of lines starting with
alphabet ‘A’ present in a text file
“LINES.TXT”.
Example: If the file “LINES.TXT” contains
the following lines,
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
Alphabets and numbers are allowed in the
password.
The function should display the output as 3.
138. PROGRAMS
19. Write a function in Python to read the
content of a text file “DELHI.TXT” and display
all those lines on screen, which are Either
starting with ‘D’ or starting with ‘M’.
DELHI.TXT File