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.
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on File Handling with Python covers all the important aspects of using files in Python right from the introduction to what fields are, all the way till checking out the major aspects of working with files and using the code-first approach to understand them better.
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
h2kinfosys is offering the IT Online Courses with Certificates ,H2kinfosys is the best place to learn online coding classes as we offer the most job oriented training led by experienced instructors through live classroom sessions. It courses online from h2kinfosys . top trending courses like learn tableau online, hadoop certification Training, python certification online and more courses register for free demo class .
https://www.h2kinfosys.com/
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on File Handling with Python covers all the important aspects of using files in Python right from the introduction to what fields are, all the way till checking out the major aspects of working with files and using the code-first approach to understand them better.
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
h2kinfosys is offering the IT Online Courses with Certificates ,H2kinfosys is the best place to learn online coding classes as we offer the most job oriented training led by experienced instructors through live classroom sessions. It courses online from h2kinfosys . top trending courses like learn tableau online, hadoop certification Training, python certification online and more courses register for free demo class .
https://www.h2kinfosys.com/
File Handling is used in C language for store a data permanently in computer.
Using file handling you can store your data in Hard disk.
http://www.tutorial4us.com/cprogramming/c-file-handling
File Handling is used in C language for store a data permanently in computer.
Using file handling you can store your data in Hard disk.
http://www.tutorial4us.com/cprogramming/c-file-handling
COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
2. FILE HANDLING IN PYTHON
Till now, we were taking the input from the keyboard/console and writing it back to the console to
interact with the user.
Sometimes, it is not enough to only display the data, or the data to be displayed may be very large or
information to be given by user for processing is too large (Ex: students’ info in a class). In such
cases, standard I/O is not feasible. Also, since video RAM is volatile, it is impossible to recover the
programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored permanently. Also, if the
output or result of the program has to be used for some other purpose later, it has to be stored
permanently. Hence, reading/writing from/to files are essential requirement of programming.
A file is a named location on disk to store related information. We can access the stored information
(non-volatile) after the program termination.
A file is some information/data which stays in the computer’s secondary storage devices.
File handling is an important part of any web application.
2
3. CONTD..
Python treats file differently as text or binary.
A text file is basically a sequence of lines containing alphanumeric characters
Database files are binary files, specifically designed to read and write through database software
Each line of a Text file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character. It ends the current line and tells the interpreter a
new one has begun.
Python has several functions for creating, reading, updating, and deleting files.
Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘n’) in Python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine-understandable binary language.
A file operation can be done in the following order.
• Open a file
• Read or Write - Performing operation
• Close the file
3
4. OPENING FILES
When we want to read or write a file, we first must open the file.
Opening the file communicates with operating system, which knows where the data for each file is stored.
The file being opened should be stored in the same folder that you are in when you start Python
When you open a file, you are asking the operating system to find the file by name and make sure the file
exists.
• This is done with the open() function
• open() returns a “file handle” - a variable used to perform operations on the file
• The open() function takes two parameters; filename, and access mode.
• There are four different modes for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
4
Other variations are:
rb – read mode, binary file
r+ - open file for both read
and write (doesn’t
overwrite the existing file)
W+- open file for both
write and read.
(Overwrites the existing
file)
5. CONTD..
Syntax:
handle = open(“filename”, “mode”)
filename is a string
mode is also a string and optional for read operation.
Handle- is a reference to an object of file class which is
required for all further operations on files
Ex:
>>>fhand=open(“demo.txt”,‘r’)
>>>print (fhand)
>>> if fhand:
print (“file opened successfully”)
Output: <_io.TextIOWrapper name='demo.txt' mode='r'
encoding='cp1252'>
file opened successfully
>>>f = open("demo.txt")
Same as
>>>f = open("demo.txt","r")
To open a file for reading, it is enough
to specify the name of the file without
mode being specified.
Note: Default python file
access mode is ‘r’ with
open()
5
Note: A text file has
newlines at the end of each
line
6. • >>>fh=open("demo1.txt",'r')
• >>>print (fh)
• Traceback (most recent call last):
• File "D:/18EC646/file1.py", line 1, in <module>
• fhand=open("demo1.txt", 'r')
• FileNotFoundError: [Errno 2] No such file or directory: 'demo1.txt‘
Note: If the file does not exist, open will fail with a traceback
and you will not get a handle to access the contents of the file:
We can use try-except block of codes to take care of this
CONTD..
6
Note: When a file gets opened
successfully, then a file object is
returned. This is known as file
handle
• A file opening may cause an error due to:
File may not exist in the specified path (when we try to read a file)
File may exist, but we may not have a permission to read/write a file
File might have got corruptedand may not be in an opening state
7. READING FROM FILES
I.
fp=open("d:/18ec646/demo.txt")
for x in fp:
print (x)
Output:
hello and welcome to
python programming
Another way to read a text file uses a list
comprehension to load the file line-by-line into a
list:
II.
>>> lines = [k.strip() for k in open('demo.txt')]
>>>print (lines)
## load the file line-by-line into a list
Output:
['hello and welcome to', 'python programming']
III. # when file size is small
>>>f = open('demo.txt')
>>>s=f.read()
>>>print (s)
## load entire file into a string
Output:
hello and welcome to
python programming
Note: If the file is located in a different location other
than the present working directory, you will have to
specify the file path
7
A file handle open for read can be treated as a sequence
of strings where each line in the file is a string in the
sequence
We can use for statement to iterate through the file
#### count the number of lines in the file
## use a for loop
fh = open('demo.txt')
count = 0
for k in fh:
count = count + 1
print('Line Count:', count)
Output:
Line Count: 2
8. CONTD..
V. you can read the whole file into one string
using the read method on the file handle.
## read the whole file into a string
## Illustration of string slicing for a file
f = open('demo.txt')
inp = f.read()
print(len(inp))
print(inp[:15])
print ()
print (inp[20:])
Output:
42
hello and welco
python programming
IV. “””to read an existing file and print
its contents”””
>>>f1 = open("demo.txt","r")
>>> print(f1.read())
Output:
hello and welcome to
python programming
Note: The open() function returns a
file object, which has
a read() method for reading the
content of the file:
read() : Returns the read
bytes in form of a string.
Reads n bytes, if n is not
specified, reads the entire
file.
8
Note: A text file can be
thought of as a sequence
of lines. To break the file
into lines, there is a
special character that
represents the end of the
line called as ‘newline
character’ (n)
>>>txt="hello n world"
>>> txt
'hello n world'
>>> print (txt)
hello
world
>>> len (txt)
13
>>> txt1=("XnY")
>>> print ("XnY")
X
Y
>>> len(txt1)
9. CONTD..
## to read first 20 characters of
the file and print
f = open("demo1.txt","r")
content= f.read(20)
print (type(content))
print (“first 20 characters are:”)
print(content)
f.close()
Output:
<class ‘str’>
first 20 characters are:
hello and welcome to
###You can return one line of the file by
###using the readline() method:
f = open("demo.txt", "r")
print(f.readline())
f.close()
Output:
This session is exclusively to deal with
###Read two lines of the file:
f = open("demo1.txt","r")
line1=f.readline()
line2=f.readline()
print(line1)
print(line2)
Output:
This session is exclusively to deal with
file handling in python
Note: It is a good practice to
always close the file after the
operation
Note: By calling readline() two
times, you can read the two first
lines:
9
10. 10
### using readlines() method
fileptr = open("demo4.txt","r")
#stores all the data of the file into the variable
content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
### file slicing example
f = open('demo4.txt‘, ‘r’)
s=f.read()
print ("the file contents are:")
print (s)
print ()
print ("total no of characters in the file are:", len(s))
print ("beginning characters of the file are:", s[:20])
print ("file contents between 30 and 80 characters: ", s[30:71])
CONTD..
Output:
['python is a easy-to-usen','open source,high-level,
object-orientedn','programming language']
Output:
the file contents are:
python is a easy-to-use
open source,high-level,object-oriented
programming language
total no of characters in the file are:86
beginning characters of the file are:python is a easy-to
file contents between30 and 70 characters: source,high-level,
object-oriented
progr
Note: It returns the list of the lines till the
end of file(EOF) is reached.
11. 11
MODIFYING FILE POINTER POSITIONS
Python provides the tell() method which is used to print
the byte numberat which the file pointer currently
exists.
fileptr = open(“demo4.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() retu
rns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
In real-world applications, we need to
change the file pointer location externally
since we may need to read or write the
content at various locations. Python provides
the seek() method which enables us to
modify the file pointer position
<file-ptr>.seek(offset[, from])
The seek() method accepts two parameters:
offset: It refers to the new position of the file
pointer within the file.
from: It indicates the reference position from
where the bytes are to be moved. If it is set to 0,
the beginning of the file is used as the reference
position. If it is set to 1, the current position of
the file pointer is used as the reference position.
If it is set to 2, the end of the file pointer is used
as the reference position.
12. 12
""“ use of seek() method
Python file method seek() sets the file's
current position at the offset.
"""
f = open("demo4.txt","r+")
print ("Name of the file: ", f.name)
line = f.readline()
print("Read Line: %s" % (line))
# Again set the pointer to the beginning
f.seek(0, 0)
line = f.readline()
print ("Read Line: %s" % (line))
### seek relative to the current position
f.seek(0, 1)
line = f.readline()
print ("Read Line: %s" % (line))
### seek relative to the current position
f.seek(0, 1)
line = f.readline()
print ("Read Line: %s" % (line))
### Reposition to 10th index position from the
beginning
f.seek(10, 0)
line = f.readline()
print ("Read Line: %s" % (line))
# Close opened file
f.close()
Output:
Name of the file: demo4.txt
Read Line:python is a easy-to-use
Read Line:python is a easy-to-use
Read Line:open source,high-level,object-oriente
Read Line:programminglanguage
Read Line:a easy-to-use
13. WRITING TO FILES
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the existing file
(file pointer at the end of the file)
"w" - Write - will overwrite any existing content; else
opens a new file to write (file pointer at the beginning of
the file)
• Open a file with ‘write’ mode using a file handler. Use
print statement with file argument to write each line
into the file and close the file
• Example script file:
• f = open(‘demo1.txt', 'w')
• print(‘ hello and welcome to ', file=f)
• print(‘Python application programming ', file=f)
• print (‘This class is about File handling in Python’,
file=f)
• f.close()
### to illustrate appending new text at the end of
#existing file
f = open("demo1.txt","a")
f.write("Now the file has more content!")
f.write (" This is to append text at the end of file")
f.close()
#open and read the file after appending:
## to check
f = open("demo1.txt", "r")
print(f.read())
13
Note: If the file handler variable is used to assign some
other file object (using open() function), then Python
closes the previous file automatically
Note:write() method doesn’t add new line character
14. EXAMPLE
“”” illustration of file write and read
operations in different ways
Creating a file for writing
entering data in file using list data”””
print("creating demo3.txt file in write
mode")
file1 = open("demo3.txt", "w")
## create a list with strings as data
L = ["This is Bangalore n", "This is
Paris n", "This is London n"]
# Writing data to a file
file1.write("Hello and welcome n")
file1.writelines(L)
file1.close()
file1 = open("demo3.txt", "r")
print("Output of the file after reading: ")
print()
print(file1.read())
print("Output of Readline function is ")
print(file1.readline())
Output:
creatingdemo3.txtfile in writemode
Outputof the file after reading:
Hello and welcome
This is Bangalore
This is Paris
This is London
Outputof Readline functionis
Hello and welcome
14
15. EXAMPLE
• """ to read a list of temperature values from a file
called temp.txt, convert them to Fahrenheit and
put the computed values to new file ftemp.txt"""
• f1 = open('ftemp.txt', 'w')
• temp= [k.strip() for k in open('temp.txt')]
• print (“Temperature in Celsius are:”)
• print (temp)
• Print(“Temperature in Fahrenheit are:”)
• for t in temp:
• t1= int(t)*9/5+32
• print (t1, file=f1)
• print (t1)
• f1.close()
Output:
temperature in Celsius are:
['23', '45', '7', '80', '98', '100']
temperature in Fahrenheit are:
73.4
113.0
44.6
176.0
208.4
212.0
15
16. CREATING A FILE
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
• Create a file called "myfile.txt":
• f = open("myfile.txt", "x") # a new empty file is created
• Create a new file if it does not exist:
f = open("myfile1.txt", "w")
16
17. FILE/DIRECTORY OPERATIONS
• To delete/rename a file, you must import the OS
module:
import os
os.remove("demo1.txt")
• May give an error, if file doesn’t exist.
• So, check if file exists, then delete it:
import os
if os.path.exists("demo1.txt"):
os.remove("demo1.txt")
else:
print("The file does not exist")
To delete an entire folder, use
the os.rmdir() method:
import os
os.rmdir(“python")
Note: You can only remove empty folders.
17
import os
os.rename (‘demo1.txt’,‘hello.txt’)
## syntax
rename(current-name,new-name)
The mkdir() method is used to create the directories
in the current working directory.
import os
#creating a new directory with the name new
os.mkdir(“python")
The getcwd() method returns the current working
directory.
import os
os.getcwd()
18. WITH STATEMENT
The with statement in Python is used for resource
management and exception handling. The with
statement simplifies exception handling by
encapsulating common preparation and cleanup
tasks.
In addition, it will automatically close the file.
there is no need to call file.close() when using
with statement.
The with statement itself ensures proper
acquisitionand release of resources.
It is when a pair of statements is to be executed
with a block of code in between.
If any exception occurs in the nested block of
code, then with statement automatically closes
the file. It doesn't let the file to corrupt. 18
Syntax:
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
with open("demo2.txt",'r') as f:
content = f.read();
print(content)
Output:
Python is a high-level,object oriented,
interpreted programminglanguage that
supportsmany domains of applications likeAI,
data science,business analyticsetc
Python is a cross-platform,open source language
that supportsmany hardware architectures
like Raspbery Pi
19. 19
# Python code to illustrate split() function
## provides output as list of elements
with open("demo4.txt", "r") as file:
data = file.readlines()
for x in data:
words = x.split()
print (words)
## defining a list
L = [“All is well n", “Life is beautiful n",
“Happiness is free n"]
# Creating a file
with open("myfile.txt", "w") as file1:
# Writing data to a file
file1.write(“These are magic statements n")
file1.writelines(L)
## writing list elements to file
file1.close() # to change file access modes
## to check whether file is written
with open("myfile.txt", "r") as file1:
# Reading form a file
print(file1.read())
Output:
These are magic statements
All is well
Life is beautiful
Happiness is free
Output:
['python','is', 'a', 'easy-to-use']
['open','source,','high-level,','object-oriented']
['programming','language']
WITH STATEMENT
20. SEARCHING THROUGH A FILE
Many times, we would like to read a file to search for some specific data within it.
Using control statements, we can extract only those lines which meet our criteria.
20
fhand = open('demo1.txt')
for k in fhand:
if k.startswith('hello') :
print(line)
fhand.close()
Output:
hello and welcome to
fhand = open('demo1.txt', 'r')
for line in fhand:
line = line.rstrip()
if line.startswith('hello') :
continue
print(line)
Output:
This class is about File handling in Python
Now the file has more content!
Output:
hello and welcome to python
application programming
fhand = open('demo1.txt', 'r')
for line in fhand:
line = line.rstrip()
if not line.startswith('hello') :
continue
print(line)
Note: We can skip a line/s in a file byusing
the continuestatement
21. 21
## allowing user to enter the file name
fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('hello'):
count = count + 1
print('There were', count, 'hello lines in', fname)
SEARCHING THROUGH A FILE
Output:
Enter the file name: demo1.txt
Therewere1 hello lines in demo1.txt
Output:
open source,high-level,object-oriented
programming language
Output:
open source,high-level,object-oriented
## using in operator to search
fhand = open('demo4.txt')
for line in fhand:
line = line.rstrip()
if 'python'in line:
continue
print(line)
fhand = open('demo4.txt')
for line in fhand:
line = line.rstrip()
if not 'open' in line:
continue
print(line)
22. HANDLING FILE OPEN ERROR WITH
TRY/EXCEPT
• When we try to open a file which doesn’t exist, python throws back an error, as seen earlier
• There is a better way of handling this using try and except blocks.
22
fname=input("Enter a file name:")
try:
fhand=open(fname)
except:
print("File cannot be opened")
exit()
count =0
for line in fhand:
count+=1
print("Line Number ",count, ":", line)
print("Total lines=",count)
fhand.close()
Output1:
Entera file name:demo3.txt
Line Number 1: Hello and welcome
Line Number 2: This is Bangalore
Line Number 3: This is Paris
Line Number 4: This is London
Total lines= 4
Output2:
Entera file name:krishna.txt
File cannot be opened
In this program, the
command to open a file is
kept within try block. If the
specified file cannot be
opened due to any reason,
then an error message is
displayed using the except
block and the program is
terminated. If the file is
opened successfully, then
we will proceed further to
perform required task using
that file.
23. DEBUGGING
23
While performing operations on files, we may need to extract required set of lines or words or
characters. So, we may use string functions with appropriate delimiters that may exist between the
words/lines of a file.
But, usually, the invisible characters like white-space, tabs and new-line characters are confusing and it
is hard to identify them properly. For example,
>>> s='1 2t 3n 4'
>>> print (s)
1 2 3
4
Here, by looking at output, its difficult make out is it displayed wrongly or deliberately done that way.
Python provides a utility function called as repr() to solve this problem. This method takes any object
as an argument and returns a string representation of that object. For example, the print() can be
modified as –
>>> print (repr(s))
'1 2t 3n 4‘