Advertisement

# What is a CSV? File Handling in Python

 File Handling in Python

What is a CSV?

CSV stands for “Comma Separated Values.” It is the simplest form of storing data in tabular form as plain text. It is important to know to work with CSV because we mostly rely on CSV data in our day-to-day lives as data scientists.

Modes:

‘r’ – to read an existing file,
‘w’ – to create a new file if the given file doesn’t exist and write to it,
‘a’ – to append to existing file content,

 

New File create

import csv

p=open("demo.csv","w")

empdata=csv.writer(p)

empdata.writerow(['id','Name'])

for i in range(2):

        print("Employee Record",(i+1))

        emid=int(input("Enter ID: "))

        emname=input("Enter Name")

        emrec=[emid,emname]

        empdata.writerow(emrec)

p.close()

 

File create without line spacing “newline

import csv

p=open("demo1.csv","w",newline="\n")

empdata=csv.writer(p)

empdata.writerow(['id','Name'])

for i in range(2):

        print("Employee Record",(i+1))

        emid=int(input("Enter ID: "))

        emname=input("Enter Name")

        emrec=[emid,emname]

        empdata.writerow(emrec)

p.close()

=> writerow() and writerows() function different

1) writerow() : writing single row at a time

 i.e : empdata.writerow(['id','Name'])

 

2) writerows(): writes all given rows to the csv file

     File Reader ()

import csv

#with open("demo.csv","r",) as p:                                       # Method -1

with open("demo.csv","r",newline='\r\n') as p:               # Method-2

     empdata=csv.reader(p)

     for r in empdata:

         print(r)

 

Note: Search() in not part of CBSE computer science students

Search()

 import csv

with open("user_info.csv", "w") as obj:

    fileobj = csv.writer(obj)

    fileobj.writerow(["User Id", "password"])

    while(True):

        user_id = input("enter id: ")

        password = input("enter password: ")

        record = [user_id, password]

        fileobj.writerow(record)

        x = input("press Y/y to continue and N/n to terminate the program\n")

        if x in "Nn":

            break

        elif x in "Yy":

            continue

with open("user_info.csv", "r") as obj2:

    fileobj2 = csv.reader(obj2)

    given = input("enter the user id to be searched\n")

    for i in fileobj2:

        next(fileobj2)

        # print(i,given)

        if i[0] == given:

            print(i[1])

            break

 


Some Important Question Answers in CSV File Handling in Python


 First Page of File Handling                                           Next Page (Binary File)

 

Q. 1 What is full form of CSV?

Ans. CSV (Comma Separated Values)

Q. 2 What is CSV file? What are its characteristics?
Ans.

·         CSV (Comma Separated Values) is a file format for data storage which looks like a text file.

·         It is used to store tabular data, such as a spreadsheet or database.

·         The information is organized with one record on each line

·         Each field is separated by comma.

·         You can choose a different delimiter character such as ‘ ‘:’ , ‘;’ , ‘|’.

·         In CSV files space-characters adjacent to commas are ignored

Q.3 When do we use CSV file?
Ans.

·         When data has a strict tabular structure

·         To transfer large data between programs

·         To import and export data

Q. 4 What are the Advantages of CSV files?
Ans. Advantages of CSV:

·         CSV is faster to handle

·         CSV is smaller in size and is easy to generate

·         CSV is human readable and easy to edit manually

·         CSV is simple to implement and parse

·         CSV is processed by almost all existing applications

Q. 5 What are the Disadvantages of CSV files?
Ans. Disadvantages of CSV:

·         There is no standard way to represent binary data

·         There is no distinction between text and numeric values

·         There is poor support of special characters and control characters

·         CSV allows to move most basic data only. Complex configurations cannot be imported and exported this way

·         There are problems with importing CSV into SQL (no distinction between NULL and quotes)

Q. 6 Which module is used to operate on CSV file?
Ans.  To read and write in CSV files we need to import csv module.

Q. 7 CSV files are opened with __________argument to supress EOL translation.
Ans. newline=’ ‘ 

Q.8 What does csv writer() function do?  
Ans.

·         The csv.writer() function returns a writer object that converts the user’s data into a delimited string.

·         This writer object can be used to write into CSV files using the writerow() function.

·         Syntax

·         writerobj = csv.writer(filehandle, delimiter=’ ‘)

Where filehandle = filehandle returned from open() function

            delimiter = delimiter to be used to separate columns

e.g.

import csv

f1=open(‘one.csv’,’w’)

w1=csv.writer(f1,delimiter = ‘,’)

Q. 9 What is the difference between writer object’s writerow() and writerows() function?
Ans. writer.writerow(row): Write the row parameter to the writer’s file object, formatted according to delimiter defined in writer function
e.g.

import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
f1.close()writer.

writerows(rows): Writes multiple rows (sequence) to the writer’s file object
e.g.

import csv
f1=open(‘one.csv’,’w’)
w1=csv.writer(f1,delimiter = ‘,’)
w1.writerow([‘S.No’, ‘Name’, ‘Marks’])
w1.writerows([[1, ‘Ronit’, 84],[2,’Nihir’,90]])
f1.close()

Q.10 What is csv reader() function?
Ans.

·         The csv.reader () function returns a reader object that helps in reading rows as per the delimiter specified.

·         This reader object is used to iterate over lines in the given csvfile

·         Each row read from the csv file is returned as a list of strings.

Syntax

readerobj = csv.reader(filehandle, delimiter=’,‘)
Where filehandle = filehandle returned from open() function
            delimiter = delimiter to be used to separate columns

e.g.

import csv
f1=open(‘one.csv’,‘r’)
w1=csv.reader(f1,delimiter = ‘,’)

 

Q.11 Which of the following file types can be opened with notepad as well as ms excel?

1.    Text Files

2.    Binary Files

3.    CSV Files

4.    None of these

Ans. c

Q. 12 What is with statement in Python?
Ans. with statement in Python is used in to simplify the management of common resources like file streams. It make the code cleaner and much more readable. For e.g. there is no need to call file.close() when using with statement.

e.g.

with open(‘file_path’, ‘w’) as file:
    file.write(‘hello world !’)

Q. 13 What does tell() method do?
Ans. It tells you the current position of cursor within the file
          Syntax:  file_object.tell()

Q. 14 What does seek() method do?
Ans. Seek() method can be used to changes the current file position
          
Syntax:

Fileobject.seek(offset[, from])
Offset:  number of bytes to be moved.
From: 0 – Beginning of the file
              1 – Current Position
              2 – End of the file


  


First Page of File Handling                                           Next Page (Binary File)