0% found this document useful (0 votes)
13 views8 pages

Python File Handling and CSV Operations

The document provides an overview of handling binary data, zipping and unzipping files, and using the Python OS module for file operations. It includes examples for reading and writing binary files, creating and extracting zip files, and performing file management tasks like renaming, deleting, and creating directories. Additionally, it covers working with CSV files for data storage and manipulation, along with string methods for data processing.

Uploaded by

Arabinda Khuntia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views8 pages

Python File Handling and CSV Operations

The document provides an overview of handling binary data, zipping and unzipping files, and using the Python OS module for file operations. It includes examples for reading and writing binary files, creating and extracting zip files, and performing file management tasks like renaming, deleting, and creating directories. Additionally, it covers working with CSV files for data storage and manipulation, along with string methods for data processing.

Uploaded by

Arabinda Khuntia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Handling Binary Data:

It is very common requirement to read or write binary data like


images,video files,audio files etc.

Example:
MyFile1=open("[Link]",mode="rb")
MyFile2=open("[Link]",mode="wb")
Byts=[Link]()
[Link](Byts)
print("New Image is : [Link]")

Working with Zipping & Unzipping


Files:
In PYTHON we can do zip and unzip files. Zip common featers are:
[Link] improve memory utilization
2. We can reduce transfor time in network
3. We can improve performance of transfor files

To create Zip file:


We have to create ZipFile class object with name of the zip
file,mode and constant ZIP_DEFLATED. This constant represents we are
creating zip file.

Syntax:
Obj=ZipFile("ZipFileName",mode,"ZipType")

Example2:
from zipfile import *
ZFile=ZipFile("[Link]","w",ZIP_DEFLATED)
[Link]("[Link]")
[Link]("[Link]")
[Link]("[Link]")
[Link]()

Unzip Operations:
ZIP_STORED represents unzip operation. This is default value and
hence we are not required to specify. Once we created ZipFile object
for unzip operation,we can get all file names present in that zip
file by using namelist() method.

Syntax:
FileObj = ZipFile("[Link]","r",ZIP_STORED)
names = [Link]()

Example:
from zipfile import *
ZFile=ZipFile("[Link]","r",ZIP_STORED)
names=[Link]()
for name in names:
print("File Name: ",name)

Working PYTHON OS Module:


The rename() Method
It takes two arguments, the current
filename and the new filename.

Syntax
[Link](current_file_name,
new_file_name)
Example:
import os
[Link]("[Link]","[Link]")

The remove() Method


It is used to delete files.

Syntax
[Link](file_name)

Example
import os
[Link]
("python.
txt")

The
mkdir()
Method
It is
used to
create
directori
es in the
current
location.

Syntax
[Link]("newdir")

Example
import os
[Link](
"PYTHON")

The
chdir()
Method
It is
used to
change
the
current
directory
.

Syntax
[Link]("Existingdir")

walk():
To display all contents of Current working directory including sub
directories

Example:
import os
for dirpath,dirnames,filenames in [Link]('.'):
print("Current Directory Path:",dirpath)
print("Directories:",dirnames)
print("Files:",filenames)
print()
NOTE:
Caution - Make sure to close all the program before running any of
the below program as these program immediately shutdown or
restart your computer.

Example:
import os
check = input("Shutdown your computer? (Y/N): ")
if check == 'N':
exit()
else:
[Link]("shutdown /s /t 1")

Example:
import os;
check = input("Shutdown your computer? (Y/N): ")
if check == 'n':
exit();
else:
[Link]("shutdown /r /t 1");

Example:
# Python Program - Shutdown and Restart Computer

import os;
print("1. Shutdown Computer");
print("2. Restart Computer");
print("3. Exit");
choice = int(input("\nEnter
your choice: "));
if(choice>=1 and choice<=2):
if choice == 1:
[Link]("shutdown
/s /t 1");
else:
[Link]("shutdown
/r /t 1");
else:
exit();

print():
It prints the given object to the standard output device (screen) or
to the text stream file.

Syntax
print(*objects, sep=' ', end='\n', file=[Link], flush=False)

1objects/values - object to the printed. * indicates that there may


be more than one object or value
2 sep - objects are separated by sep. Default value: ' '
3 end - end is printed at last
[Link] - must be an object with write(string) method. If omitted
it, [Link] will be used which prints objects on the screen.
5. flush - If True, the stream is forcibly flushed. Default
value:
False
Example:
Sfile=open("[Link]",'w')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile)

Example:
Sfile=open("[Link]",mode='w')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile)
[Link]()

Example:
Sfile=open("[Link]",'w')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile)
[Link]()
print("Success")

Example:
Sfile=open("[Link]",'a')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile,flush=True)
[Link]()
print("Success")

NOTE:
Flush which allows the user to decide if he wants his output to be
buffered or not. The default value of this is False meaning the
output will be buffered.

Python Data Processing and Encoding:


CSV (Comma Separated Values/Data) files to store data that are in
tabular format into plain text & each line is treated as a data
record in the file.

Define Delimiter:
It is a sequence of one or more characters used to specify the
boundary between separate.
Example:
A delimiter is the comma character, or Space, or Gap or Colon etc..
a CSV file in Notepad, Microsoft Excel, OpenOffice Calc, and
Google Docs.

Syntax: CSV formated text..!!


fname,lname,age,salary
nancy,davolio,33,$30000
erin,borakova,28,$25250
tony,raphael,35,$28700

In PYTHON Environment we can able to work with csv files, we can


use built-in module is called CSV.
1. Open the file on required mode
2. Create the csv file represented object
3. Read or write or update the data
Syntax:
import csv

CSV Functions
1 [Link]
2 [Link]

EXAMPLE:Writing data in CSV file (Creating CSV File)


import csv
try:
with open("[Link]",mode='w',encoding='utf-8') as FP:
a=[Link](FP,delimiter=';')
data=[['STOCK','SALES','PRICE'],
['100','90','90$'],
['300','100','100$'],
['100','200','200$']]
[Link](data)
print("CSVFileCreatedSuccessfully")
except IOError:
print("SorryCSVFileUnableTOCreate")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

EXAMPLE:Appending data in CSV file..!!


import csv
try:
with open("[Link]",mode='a',encoding='utf-8') as FP:
a=[Link](FP,delimiter=',')
data=[['10','9','9$'],
['0','0','0$'],
['10','2','2$']]
[Link](data)
print("CSVFileAppendSuccessfully")
except IOError:
print("SorryCSVFileUnableTOAppend")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")

EXAMPLE: Reading CSV File Without Builtin Methods..!!


try:
with open("[Link]",mode='r',encoding='utf-8') as
FP:
for data in FP:

print(data)
print("CSVFileReadS
uccessfully")
except IOError:
print("SorryCSVFileUnableToAppend")
print("ServerWriteProtected")
finally:
print("FinallyBlockSuccess")
Example:Reading CSV File
import csv
with open("[Link]",'r') as FP:
a=[Link](FP)
data=[]
for row in a:
if len(row)!=0:
data=data+[row]
print(data)

#without using csv module


path="[Link]"
lines=[line for line in
open(path)]
print(lines[0])

Python String strip()


Method
It returns a copy of the string in which all chars have been
stripped from the beginning and the end of the string (default
whitespace characters).

Syntax:
[Link]([chars]);

Example:
path="[Link]"
lines=[line for line in open(path)]
print(lines[0])
print(lines[1].strip())

Python String split() Method


It returns a list of all the words in the string, using str as the
separator.

Syntax
[Link](",").

Example:
path="[Link]"
lines=[line for
line in
open(path)]
print(lines[0])
print(lines[1].strip())
print(lines[1].strip().split(','))

Examples::

MyFile1=open("[Link]",mode="rb")
MyFile2=open("[Link]",mode="wb")
Byts=[Link]()
[Link](Byts)
print("New Image is : [Link]")

MyFile1=open("[Link]",mode="rb")
MyFile2=open("[Link]",mode="wb")
x=[Link]()
[Link](x)
print("New Image is : [Link]")
from zipfile import *
ZFile=ZipFile("[Link]","r",ZIP_DEFLATED)
[Link]("[Link]")
[Link]("[Link]")
[Link]("[Link]")
[Link]()
print("Zip file format created
successfully")

from zipfile import *


ZFile=ZipFile("[Link]","w",ZIP_DEFLATED)
[Link]("[Link]")
[Link]("[Link]")
[Link]("[Link]")
[Link]()
print("Zip file format created
successfully")

from zipfile import *


ZFile=ZipFile("[Link]","r",ZIP_STORED)
names=[Link]()
for name in names:
print("File Name: ",name)

from zipfile import *


ZFile=ZipFile("[Link]",'r',ZIP_STORED)
names=[Link]()
for name in names:
print(name)
print("AllFilesUnC
ompressedSuccessfu
lly")

import os
for fnames in [Link]('.'):
print(fnames)
#. is current directory
#.. is parent/root
directory

import os
print([Link]("[Link]"))

Sfile=open("[Link]",'w')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile)

Sfile=open("[Link]",'w')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile)
[Link]()

Sfile=open("[Link]",'w')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile)
[Link]()
print("Success")
Sfile=open("[Link]",'a')
print("Hello Python: ",file=Sfile)
print("Data Engineer: ",file=Sfile,flush=True)
[Link]()
print("Success")

import csv
print(dir(csv))

.txt -- word
format
.doc -- .txt
xls -- word
format
.doc -- xls
format
.txt -- xls
format

.csv -- file
create open
with any format

import csv
try:
with
open("
MyFile
.csv",
mode='
w',enc
oding=
'utf-
8') as
FP:
PyData=[Link](FP,delimiter=",")
Python CSVSData=[['STOCK','SALES','PRICE'],
tutorial - read write
CSV ['100','90','$90'],
['300','100','$100'],
['10','10','$10']]
[Link](SData)
[Link]
print("CSV FIle Creaed Successfully")
except IOError:
print("Sorry CSV File Unable To
Create")
print("Sever Write Protected")
finally:
print("FinallyBlockSuccess
")

You might also like