The document provides an overview of basic file handling operations in Python, including opening, reading, writing, and closing files. It emphasizes the importance of using the 'with' statement for automatic resource management and discusses file pointer operations for navigating through files. Additionally, it covers error handling, practical examples, and best practices for efficient file handling.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
10 views
Files in Python
The document provides an overview of basic file handling operations in Python, including opening, reading, writing, and closing files. It emphasizes the importance of using the 'with' statement for automatic resource management and discusses file pointer operations for navigating through files. Additionally, it covers error handling, practical examples, and best practices for efficient file handling.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
File Handling
Temata) a)
DANZA @ CLO aAN
ntti Co ge eto te
aro Camaros ene mtg
ene outen fabs
same em be
anode hte
pees aga,
roel eects erd te nar te crn edpemin
‘oye tee “eben
‘ane = ene)
1 print ope fe nse eect
tena)
“Covfetorcer tres dee! nating 912029Basic File Operations
1 Opening ies
‘espen tacton
ne nratanea tsar peat ieactthe
opm ie or rece (eft mde)
fies sen somes)
te = en sae“)
‘Tepe nn due retest cose.
‘hsp ge eo, may py nets ate many
‘Teagan ks esa ere fleas
Tefen bye
‘hired sind lag a gi ay.
than «cen tor sorte?)
ean oe te
Lop ere each ine nthe fle
Prine Lie out", cam)
2 Reading Files
vo) etecte fenestra
ino de herent e
resend ate ones ote te li
ame
Insetecw cal, ee et 20/9425 acto) ad Revere at
Ths atti of rare ie whl wri aan a
sth on sorele.te 7) ae Hes
Pristen stip)Basic File Operations (Continued)
23 Whiting Fes
“Tone te e pnaeade) T e a eg eece Te
‘ell mde eon reo cine: You eerton
Example Using wee)
en cut wes) 9 fot
‘etait he sc wo)
Nene ep es)
sample Using writeLtnes(3
ome = et ne scan ie)
cmt aston ta fo
+ ERR rst este
en mit na i he A de rary,
4 Anpencing Fes
png ns rg rutin! te nao te
Vind ot to
‘hon eee te) th
Town eae ean ete
ae ge ongFile Closing and the with Statement
Manual Closing
After working with a fil, you must close it to free resources.
file = open("sanple.txt', "r')
# Perform File operations
file.close() # Manvally close the file
Automatic Resource Management with with
Using the with statement ensures thatthe file is automatically
‘closed after exiting the block, even if an exception occurs,
Example
with open(*sample.txt", 'r*) as file:
content = file.read()
# The file 4s automatically closed after the
wuith’ block ends.
Why Use with?
Prevents resource leaks,
‘Automatically handles file closure, reducing the risk of errors.File Pointer Operations
By combining S@8k() and t611(), we can precisely control the file pointer and navigate through the file as needed
Changing Position with seok()
‘The S€8K() function allows us to move the file pointer to a specific byte
Position in the fe
We can pass two arguments to S86K(): the offset (numberof bytes
‘to move) and the whence (reference point, usually 0 forthe
beginning ofthe fle)
+ This lets us position the file pointer wherever we need it, so we can
read of write from that point
ith open("sample.txt", ‘p*) as file:
file.seek(5) # Move pointer to Sth byte
print(file.read()) # Reads from 5th byte
In this example the file pointer is moved tothe Sth byte, and then the
content from that position is read and printed.
Checking Position with telld
+ The te11() function retums the current position ofthe file pointer in
terms of bytes from the beginning of the fe
‘tis useful for keeping track of where we are inthe file
ith open("sample.txt', 'n') as File:
file.seck(5) # Move to the Sth byte
print(#ile.tell()) # outputs 5
+ Here, after moving the file pointer tothe th byte wth S@ek(), the
‘Ee11() function confirms that the pointer is indeed at byte 5.Working with Binary Files
come
1 easing Diary ota
so open
srinkata)
Error Handling in File Operations
set ncptials hand lalate ore pace
print" errr ecard while handling the fie.*)Practical Examples
splits based on whitespace.
Reversing File Lines
4)
Get reverse File lines( Filename):
Wath’ open(#irename, ‘e*) as file:
afhes = #ilerréad]ines()
for line in reversed lines
print(line.stript))
# Call the function with a sanple file
Feverse file -lines( sample. txt")
F
and = open(“helio.txt", “r”
ene ieee ite cree
for pelge(linesSerip0 (32-2)
Pre class)
‘huh words = Len(content.-sp1ie()) calculates the total number of words by sk
‘eadlines(): reads al lines fom ile and stores them in alist where each element corresponds toa ine inthe file
‘Revers@d(1n@S) Reverses the order ofthe lines. Instead of iterating through the lines inthe original order, it processes them from the ast ne othe first
oirtentsSpL4ELINES() Spits the string into alist of lines using line breaks (NA) as delimiters
‘Lines ¢64P(): Removes any eading/traling whitespace (Including newline characters)
ing the content into alist of words using the LSp14E() method, which
fnum_ines = en(content.plitlines() calculates the total numberof ines by spliting the content nto alist of nes using sspLStLines().
File Statistics
det File statistics(filenare):
withropen(Filengee,"re)oas File:
content= Ple:neadl)
‘oun_ characters = len(congent
rumcyorde = fencer: SQ) ayy
feturn'num_cnaracters, num words, flm_Lines
#,Ca11 the function, and display the results
Characters, words, "Lines = File statistics( sample. txt"
Spans iS hardeters: character sy, Wands! (hota, “LinesPractical Examples
Checking Palindrome Lines
def check palindrone_Lings( filename
SMeftopencFilenanes SSS as Fie:
‘for line in file:
slopes < Tine ses0Q)
41;
print Patindrone:* {¥ripped)")
Character Count in file
de count characters in #iteFLenaee):
Sieh Spen(eiithage, or) as file:
‘contest a File’ readt)
tor SRETIS content
char courthcaeed
retutn crane eobat
4 Call the function and print the resul
Boint(coune characters th fHiet sample: txt")
‘char_count.get(char, @) + 2Practical Example
‘Write a program to read through a file and print the contents of the file line by line) all in upper case.
4 Progran to read a File and print its contents in uppercase
4 Eunction to read and print file contents in uppercase
def print File uppercase(#i1e_nane
with open(file name, ‘r*) as file:
or line 1a file:
Bprinctline:vpper(), end="") # Convert to uppercase and print
pron: The file "{File nane)* was not found.")
except Exception ase:
Print (fan error occurred: {e}")
$ Input: File nane,
falePnene’ = Snput{"Enter the file naxe:
4 Call the function
brint_ile_Uppercase(File_nane)Wate Python pogram that perform the olosing iss
1 Reads file specified bythe wer
2. Prin al ins dat start with spoiieproix AOR)
3. nal ines hat contain a peific substring (ee, DULAC).
44. Hanles he following:
«Ext newline character in the
1 Skipping relevant ins using the COM tstsment
4+ Exorpions for misig fils or othe rors during le handling
‘Use sting methods such as Sans) and find). Ensure he ile is losed properly fer reading, and provide meaningful eror messages if the les not found or apotber
Example Output (for mbox-short.txt):
Lines starting with the prefix: From:
From: stephen.marquard@uct.ac.za
From: louis@media. berkeley.edu
From: zqian@unich.edu
From:
Lines containing the substring: @uct.ac.za
From: stephen.narquard@uct.ac.za
X-Authentication-Warning: set sender to stephen.marquard@uct.ac.za using -f
Author: stephen.marquard@uct.ac.za
From: david.horwitz@uct.ac.za
X-Authentication-Warning: set sender to david.horwitz@uct.ac.za using -f
Author: david.horwitz@uct.ac.zaaeBest Practices for File Handling
3) Use with Statement 2) Handle Exceptions Gracefully
Ensures proper closure of les, even ding Prevant program erashes by using ty
exceptions except blocks.
4 Oplimize for Large Files
Use resdine) oF terate over the file instead of loading the entve content into memory.
Common Errors and Solutions
Error cause
FieNotrounct or File does nat exist.
Permissiontiror Insufficient permissions.
LUncupportedOperation ‘operation not alowed in fle mode
\oeror ‘General /0 ero.
3) Avoid Unnecessary File Overwrites
Use appropriate modes (iw, 2, otc) based
onthe operation
Solution
‘Check the fie path or exeate the fle
‘Check file permission.
Use the corect mode (¢.9)
Use ty-excopt to handle gracefully