[go: up one dir, main page]

0% found this document useful (0 votes)
22 views6 pages

CS 5 MARKS (Lesson 13 To 14)

12 CS 5mark les

Uploaded by

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

CS 5 MARKS (Lesson 13 To 14)

12 CS 5mark les

Uploaded by

free2468fjadgk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

ALWAYS LIVE WITH GOD

12TH COMPUTER SCIENCE 5 Marks ISAAC EBINEZAR V


3. Write the different methods to read a File
Lesson 13 PYTHON AND CSV FILES
in Python.
1. Differentiate Excel file and CSV file. There are two ways to read a CSV file.
Excel CSV 1. Use the csv module‟s reader function
2. Use the DictReader class.
Excel is a binary file CSV format is a plain 1. Use the csv module‟s reader function
that holds information text format with a  The reader function is designed to take
about all the series of values each line of the file and make a list of all
worksheets in a file, separated by columns.
including both commas.  Using this function one can read data from
content and csv files of different formats like quotes ("
formatting "), pipe (|) and comma (,).
 csv.reader() work with list/tuple.
XLS files can only be CSV can be opened  The syntax for csv.reader() is
read by applications with any text editor in csv.reader(fileobject,delimiter,fmtparams)
that have been Windows like where
especially written to notepad, MS Excel, file object: passes the path and the mode
read their format, and OpenOffice, etc. of the file
can only be written in delimiter : an optional parameter containing
the same way. the standard dilects like , | etc
can be omitted
Excel is a CSV is a format for fmtparams: optional parameter which help
spreadsheet that saving tabular to override the default values of
saves files into its information into a the dialects like
own proprietary delimited text file with skipinitialspace,quoting etc. Can
format viz. xls or xlsx extension .csv be omitted
 Example:
Excel consumes Importing CSV files import csv
more memory while can be much faster, with open('c:\pyprg\sample1.csv','r',newline„=‟) as F:
importing data and it also consumes reader = csv.reader(F)
less memory for row in reader:
print(row)
2. Tabulate the different mode with its F.close()
meaning. 2. Use the DictReader class.
Mode Description  To read a CSV file into a dictionary can be
'r' Open a file for reading. (default) done by using DictReader method of csv
'w' Open a file for writing. Creates a new module which creates an object which
file if it does not exist or truncates the maps data to a dictionary.
file if it exists.  DictReader works by reading the first line
'x' Open a file for exclusive creation. If the of the CSV and using each comma
file already exists, the operation fails. separated value in this line as a dictionary
'a' Open for appending at the end of the key.
file without truncating it. Creates a new  csv.DictReader() work with dictionary.
file if it does not exist.  Example:
't' Open in text mode. (default) import csv
filename = „c:\pyprg\sample8.csv‟
'b' Open in binary mode. input_file =csv.DictReader(open(filename,‟r‟))
'+' Open a file for updating (reading and for row in input_file:
writing) print(dict(row))

Page 1 of 6
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE 5 Marks ISAAC EBINEZAR V
4. Write a Python program to write a CSV 5. Write the rules to be followed to format
File with custom quotes. the data in a CSV file.
import csv 1) Each record (row of data) is to be located
csvData = [[„SNO‟,‟Items‟],[„1‟,‟Pen‟],[„2‟,‟Book‟], on a separate line, delimited by a line
[„3‟,‟Pencil‟]]
csv.register_dialect(„myDialect‟,delimiter=„|‟,quotechar
break by pressing enter key.
=„”‟,quoting=csv.QUOTE_ALL) For example:
with open(„c:\pyprg\ch13\quote.csv‟,„w‟,newline„=‟) as xxx,yyy
csvFile: denotes enter Key to be pressed
writer = csv.writer (csvFile, dialect=‟myDialect‟) 2) The last record in the file may or may not
writer.writerows(csvData)
print(“writing completed”)
have an ending line break. For example:
csvFile.close() ppp, qqq
yyy, xxx
3) There may be an optional header line
appearing as the first line of the file with
the same format as normal record lines.
The header will contain names
corresponding to the fields in the file and
should contain the same number of fields
as the records in the rest of the file. For
example:
field_name1,field_name2,field_name3
aaa,bbb,ccc
zzz,yyy,xxx CRLF(Carriage Return and Line
Feed)
4) Within the header and each record, there
may be one or more fields, separated by
commas. Spaces are considered part of a
field and should not be ignored. The last
field in the record must not be followed by
a comma. For example: Red , Blue
5) Each field may or may not be enclosed in
double quotes. If fields are not enclosed
with double quotes, then double quotes
may not appear inside the fields. For
example:
"Red","Blue","Green"
#Field data with doule quotes
Black,White,Yellow
#Field data without doule quotes
6) Fields containing line breaks (CRLF),
double quotes, and commas should be
enclosed in double-quotes. For example:
Red, “,”, Blue CRLF
# comma itself is a field value.so
it is enclosed with double quotes
Red, Blue , Green
7) If double-quotes are used to enclose fields,
then a double-quote appearing inside a
field must be preceded with another double
quote. For example:
““Red””, ““Blue””, ““Green”” CRLF
# since double quotes is a field
value it is enclosed with another
double quotes
, , White

Page 2 of 6
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE 5 Marks ISAAC EBINEZAR V
3. Write the syntax for getopt() and explain
Lesson 14 IMPORTING C++ PROGRAMS
its arguments and return values
IN PYTHON
Python getopt module
1. Write any 5 features of Python.  The getopt module of Python helps you
1) Python uses Automatic Garbage Collection to parse (split) command-line options
whereas C++ does not. and arguments. This module provides
2) C++ is a statically typed language, while getopt() method to enable command-line
Python is a dynamically typed language. argument parsing.
 getopt.getopt function
3) Python runs through an interpreter, while
This function parses command-line
C++ is pre-compiled.
options and parameter list. Following is
4) Python code tends to be 5 to 10 times the syntax for this method –
shorter than that written in C++. <opts>,<args>=getopt.getopt(argv,
5) In Python, there is no need to declare options, [long_options])
types explicitly where as it should be done  Here is the detail of the parameters −
in C++ 1) argv − This is the argument list of
6) In Python, a function may accept an values to be parsed (splited). In our
argument of any type, and return multiple program the complete command will
values without any kind of declaration be passed as a list. For example
beforehand. Whereas in C++ return 2) c:\pyprg\pali.py -i c:\pyprg\pali_cpp
statement can return only one value. 3) options − This is string of option letters
2. Explain each word of the following that the Python program recognize as,
command. for input or for output, with options (like
Python <filename.py> -<i> <C++ filename „i‟ or „o‟) that followed by a colon (:).
without cpp extension> Here colon is used to denote the
mode.
Python keyword to execute the 4) long_options −This contains a list of
Python program from strings. Argument of Long options
command-line should be followed by an equal sign
'='. In our program the C++ file name
filename.py Name of the Python program
along with its path will be passed as
to executed
string and „i‟ i will be also passed to
-i input mode indicate it as the input file.
 getopt() method returns value consisting
C++ filename name of C++ file to be of two elements. Each of these values
without cpp compiled and executed are stored separately in two different list
extension (arrays) opts and args .
 Example:
opts,args=getopt.getopt(argv,"i:",['ifile='])
 where opts contains [('-i',
'c:\\pyprg\\p4')]
 -i :- option - mode should be
followed by : (colon)
 'c:\\pyprg\\p4' value - absolute path of
C++ file.
 In our examples since the entire
command line commands are parsed
and no leftover argument, the second
argument args will be empty []. If args is
displayed using print() command it
displays the output as [].
>>>print(args)
[]

Page 3 of 6
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE 5 Marks ISAAC EBINEZAR V
4. What is the purpose of sys,os,getopt  where each argument contains
module in Python.Explain. os.system : function system() defined in os
1) Python‟s sys module: module to interact with the operating
 This module provides access to builtin system
g++ : General compiler to compile C++
variables used by the interpreter. One
program under Windows Operating
among the variable in sys module is system.
argv. variable_name1: Name of the C++ file along with its
 sys.argv is the list of command-line path and without extension in string
arguments passed to the Python format
program. mode : To specify input or output mode. Here
 argv contains all the items that come via it is o prefixed with hyphen.
the command-line input, it's basically a variable_name2: Name of the executable file without
list holding the command-line arguments extension in string format
of the program.  For example :
 To use sys.argv, import sys should be os.system('g++ ' + cpp_file + ' -o ' + exe_file)
used. 3) Python getopt module:
 The first argument, sys.argv[0] contains  The getopt module of Python helps you
the name of the python program to parse (split) command-line options
(example pali.py) and arguments. This module provides
 and sys.argv [1]is the next argument getopt() method to enable command-line
passed to the program (here it is the argument parsing.
C++ file), which will be the argument  getopt.getopt function
passed through main ( ). This function parses command-line
 For example options and parameter list. Following is
main(sys.argv[1]) the syntax for this method –
2) Python's OS Module: <opts>,<args>=getopt.getopt(argv,
 The OS module in Python provides a options, [long_options])
way of using operating system  Here is the detail of the parameters −
dependent functionality. 1) argv − This is the argument list of
 The functions that the OS module allows values to be parsed (splited). In our
you to interface with the Windows program the complete command will
operating system where Python is be passed as a list. For example
running on. 2) c:\pyprg\pali.py -i c:\pyprg\pali_cpp
 os.system(): Execute the C++ compiling 3) options − This is string of option letters
command (a string contains Unix, C that the Python program recognize as,
command which also supports C++ for input or for output, with options (like
command) in the shell (Here it is „i‟ or „o‟) that followed by a colon (:).
Command Window). Here colon is used to denote the
 For Example to compile C++ program mode.
g++ compiler should be invoked. 4) long_options −This contains a list of
 To do so the following command is strings. Argument of Long options
used. should be followed by an equal sign
os.system („g++ ‟ + <variable_name1> '='. In our program the C++ file name
+„ -<mode> ‟ + <variable_name2>) along with its path will be passed as
string and „i‟ i will be also passed to
indicate it as the input file.
 getopt() method returns value consisting
of two elements. Each of these values
are stored separately in two different list
(arrays) opts and args .
 Example:
opts,args=getopt.getopt(argv,"i:",['ifile='])

Page 4 of 6
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE 5 Marks ISAAC EBINEZAR V
5. Write a Python program to execute the
following c++ coding
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file
welcome.cpp
Python Program:
#Now select File→New in Notepad and type
the Python program
# Save the File as pali.py . Program that
compiles and executes a .cpp file
# Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
import sys, os, getopt
def main(argv):
opts, args = getopt.getopt(argv, "i:")
for o, a in opts:
if o in "-i":
run(a)
def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
os.system('g++'+inp_file+'-o'+ exe_file)
os.system(exe_file)
if __name__=='__main__':
main(sys.argv[1:])

Page 5 of 6
ALWAYS LIVE WITH GOD
12TH COMPUTER SCIENCE 5 Marks ISAAC EBINEZAR V

Page 6 of 6

You might also like