0% found this document useful (0 votes)
95 views

File Handling CSV Files Notes 3

A CSV (comma-separated values) file is a plain text file used to store tabular data, with each field separated by a comma. CSV files are commonly used to export data from databases and spreadsheets. The document discusses the structure and characteristics of CSV files, including that they contain one record per line with comma-separated fields. It also describes how to read from and write to CSV files in Python using the built-in CSV library, including using the reader and writer objects to iterate through rows of data. Finally, the document provides an example of writing data to a CSV file and then reading it back.

Uploaded by

SANTOSH KEKANE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

File Handling CSV Files Notes 3

A CSV (comma-separated values) file is a plain text file used to store tabular data, with each field separated by a comma. CSV files are commonly used to export data from databases and spreadsheets. The document discusses the structure and characteristics of CSV files, including that they contain one record per line with comma-separated fields. It also describes how to read from and write to CSV files in Python using the built-in CSV library, including using the reader and writer objects to iterate through rows of data. Finally, the document provides an example of writing data to a CSV file and then reading it back.

Uploaded by

SANTOSH KEKANE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DOHA MODERN INDIAN SCHOOL

Grade: 12 C.S.
Chapter: File Handling
CSV file operations
What is a CSV File?
• A CSV file (Comma Separated Values) is a type of plain text file that uses specific
structuring to arrange tabular data.
• CSV is a file format for data storage which looks like a text file. The information is
organized with one record on each line and each field is separated by comma.
• Because it’s a plain text file, it can contain only actual text data.
• The structure of a CSV file is given away by its name. Normally, CSV files use a
comma to separate each specific data value.
• In general, the separator character is called a delimiter, and the comma is not the
only one used.
• Other popular delimiters include the tab (\t), colon (:) and semi-colon (;)
characters. Properly parsing a CSV file requires us to know which delimiter is being
used.
Example:
column 1 name, column 2 name, column 3 name
first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
……………………...
………………………….
Where do CSV Files come from?
 CSV files are normally created by programs that handle large amounts of data.
 They are a convenient way to export data from spreadsheets and databases as well
as import or use it in other programs.
For example, you might export the results of a data mining program to a CSV file and
then import that into a spreadsheet to analyze the data, generate graphs for a
presentation, or prepare a report for publication.
CSV File Characteristics
 One line for each record
 Comma separated fields
 Space-characters adjacent to commas are ignored
 Fields with in-built commas are separated by double quote characters.
When Use CSV?
 When data has a strict tabular structure.
 To transfer large database between programs.
 To import and export data to office applications.
 To store, manage and modify shopping cart catalogue.
CSV Advantages
 CSV is faster to handle
 CSV is smaller in size
 CSV 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.
CSV Disadvantages
 No standard way to represent binary data.
 There is no distinction between text and numeric values.
 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.
 Problems with importing CSV into SQL (no distinction between NULL and quotes).
Parsing CSV Files With Python’s Built-in CSV Library
 The csv library provides functionality to both read from and write to CSV files.
 Designed to work out of the box with Excel-generated CSV files, it is easily adapted
to work with a variety of CSV formats.
 The csv library contains objects and other code to read, write, and process data
from and to CSV files.
Reading CSV Files with csv library
 Reading from a CSV file is done using the reader object. The CSV file is opened as a
text file with Python’s built-in open() function, which returns a file object. This is
then passed to the reader, which does the heavy lifting.
How to Read a CSV File
To read data from CSV files, you must use the reader function to generate a reader object.
The reader function is developed to take each row of the file and make a list of all columns.
Then, you have to choose the column you want the variable data for.
Example:
#import necessary modules
import csv
with open('D:\data.csv','r')as f:
data = csv.reader(f)
for row in data:
print(row)
Output:
['Programming language; Designed by; Appeared; Extension']
['Python; Guido van Rossum; 1991; .py']
['Java; James Gosling; 1995; .java']
['C++; Bjarne Stroustrup;1983;.cpp']
Output:
How to write CSV File
When you have a set of data that you would like to store in a CSV file you have to use
writer () function.
To iterate the data over the rows (lines), you have to use the writerow() function.
Example:
#import necessary modules
import csv
with open('D:\MyCSVData.csv', mode='w') as file:
data = csv.writer(file, delimiter=',')
#way to write to csv file
data.writerow(['Programming language', 'Designed by', 'Appeared', 'Extension'])
data.writerow(['Python', 'Guido van Rossum', '1991', '.py'])
data.writerow(['Java', 'James Gosling', '1995', '.java'])
data.writerow(['C++', 'Bjarne Stroustrup', '1985', '.cpp'])

Write and Read CSV FILE


Example:
import csv
#csv file writing code
with open('d:\\a.csv','w') as newFile:
newFileWriter = csv.writer(newFile)
newFileWriter.writerow(['user_id','beneficiary'])
newFileWriter.writerow([1,'xyz'])
newFileWriter.writerow([2,'pqr'])
newFile.close()
#csv file reading code
with open('d:\\a.csv','r') as newFile:
newFileReader = csv.reader(newFile)
for row in newFileReader:
print (row)
newFile.close()

Explanation:
writing and reading operation in CSV file is very easy. First of all we have to import csv
module for file operation/method call.
For writing ,we open file in ‘w’ writing mode using open() method which create newFile
like object.
Through csv.writer() method ,we create writer object to call writerow() method to write
objects.
Similarly for reading ,we open the file in ‘r’ mode and create newFile like object, further
we create newfilereader object using csv.reader() method to read each row of the file.
Three file opening modes are there ‘w’,’r’,’a’.
‘a’ is for append. After the file operation close it, for closing the opened file using close()
method.
Sample Questions & Solutions

1. To read twelve characters from a file object infi, we use_______________


Answer:
infi.read(12)
2. To read the entire remaining contents of the file as a string from a file object infi,
we use_________
Answer:
infi.read( )
3. To read the next line of the file from a file object infi, we use_____________
Answer:
infi.readline( )
4. To read the remaining lines of the file from a file object infi, we use___________
Answer:
infi.readlines( )
5. The readlines() method returns____________
Answer:
a list of lines
6. Which function is used to write all the characters?
Answer:
write( )
7. Which function is used to write a list of strings in a file?
Answer:
writelines( )
8. What is the difference between r+ and w+ modes?

Answer: In r+ mode, the pointer is initially placed at the beginning of the file and for w+,
the pointer is placed at the end.

9. What is the significance of file-object?

Answer: Through a file-object only, a Python program can work with files stored on hardware. File
objects are used to read and write data to a file on disk.

10. How is file open() function different from close() function?

Answer: The open() opens the mentioned file in specified file mode and attaches it to the
file object so that file operations can be performed on it.

A close() function breaks the link of file object and the file on the disk. After close(), no
tasks can be performed on that file through the file object(or the file handle).

11. Write a single loop to display all the contents of a text file poem.txt after
removing leading and trailing whitespaces.
Answer:
for line in file(“poem.txt”):
print(line.strip())

12. When a file is opened for output, what happens when?


i)The mentioned file does not exist
ii) The mentioned file does exist
Answer:
i)A new file bearing the mentioned filename will be created.
ii)The existing contents of the files are overwritten.

13. When do you think text files should be preferred over binary files?
Answer:
Text files should be preferred over binary files when most of the data stored contains text
(as test files cannot store data in other forms. E.g., images, etc) and requires human
readability.

14. What is the output of following code? Justify your answer.


fh=open(“poem.txt”, “r”)
size=len(fh.read())
print(fh.read(5))
Answer:
No output
Explanation: The fh.read() of line 2 will read the entire file content and place the file pointer
at end of file. For the fh.read(5), it will return nothing as there are no bytes to be read from
EOF thus print() statement prints nothing.

15. Read the code given below and answer the question:
fh=open(“main.txt”, “w”)
fh.write(“Bye”)
fh.close()
If the file contains “GOOD” before execution, what will be the contents of the file after
execution of this code?
Answer:
The file would now contain “Bye” only, because when an existing file is opened in write mode
(“w”), it truncates the existing data in the file.

16. What is the difference between “w” and “a” modes?


Answer:

17. Write a function remove_lowercase() that accepts two filenames, and copies all
lines that do not start with a lowercase letter from the first file into the second
file.
Answer:
def remove_lowercase(infile,outfile):
output=file(outfile,"w")
for line in file(infile):
if not line[0] in "abcdefghijklmnopqrstuvwxyz":
output.write(line)
output.close()

18. Write a program to display all the records in a file along with line/record
number.
Answer:
fh=open("d:\\result.dat","r")
count=0
rec=""
while True:
rec=fh.readline()
if rec=="":
break
count=count+1
print(count,rec,end=" ")
fh.close()

19. A text file contains alphanumeric text (say result.txt). Write a program that
reads this text file and prints only the numbers or digits from the file.
Answer:
f=open("d:\\result.txt","r")
for line in f:
words=line.split()
for i in words:
for letter in i:
if(letter.isdigit()):
print(letter,end='')
f.close()
20. Write code to print just the last line of a text file “result.txt”.
Answer:
f=open("d:\\result.txt","r")
lineList=f.readlines()
print("Last line=",lineList[-1])
f.close()

21. Write code to open file contacts.txt with shown information and print it in the
following form:
Name: <name> Phone:<phone number>
Answer:
f=open("d:\\contacts.txt","r")
line=f.read()
val=line.split(",")
print("Name:",val[0]," ","Phone:",val[1])
f.close()

22. Write a method in python to read the content from a text file “result.txt” line by
line and display the same on screen.
Answer:
f=open("d:\\result.txt","r")
line=" "
while line:
line=f.readline()
print(line)
f.close()

23. Write a method in python to write multiple lines of text contents into a text file
“myfile.txt”.
Answer:
fileout=open("d:\\myfile.txt","w")
for i in range(5):
line=input("Enter line:")
fileout.write(line+'\n')
fileout.close()
24. Write a function in python to count the number of lines in a text file ‘STORY.TXT’
which is starting with an alphabet ‘A/a’. (Board Question)
Answer:
def COUNTLINES():
file=open("STORY.TXT","r")
lines=file.readlines()
count=0
for w in lines:
if w[0]=='A' or w[0]=='a':
count=count+1
print("Total lines",count)
file.close()

25. Write a method/function DISPLAYWORDS() in python to read lines from a text


file STORY.TXT, and display those words, which are less than 4 characters.
(Board Question)
Answer:
def DISPLAYWORDS():
c=0
file=open('d:\\result.txt','r')
line = file.read()
word = line.split()
for w in word:
if len(w)<4:
print(w)
file.close()

26. Write a program in python to type text in a file till ~ is pressed as rightmost
character.
Answer:
f=open("d:\\a.txt","w")
s=' '
print("Type text for file, press ~ as rightmost character for exit/save contents")
while s!='~':
s=input()
f.write(s+"\n")
s=s[-1:]
f.close()
print("file contents saved")

27. Write a Program in python to read entire text file.


Answer:
f=open("d:\\a.txt","r")
s=f.read()
print(s)
f.close()

28. Write a Program in python to append text at the end of text file.
Answer:
f=open("d:\\a.txt","a")
s=input("enter a string to add at the end of file")
f.write(s)
f.close()
29. Write a Program in python to read line by line from text file .
Answer:
f=open("d:\\a.txt","r")
for t in f.readlines():
print(t,end="")
f.close()

30. Write a Program in python to read entire file line by line in a list.
Answer:
f=open("d:\\a.txt","r")
t=f.readlines()
print(t)
f.close()
31. Write a Program in python to read each word separately.
Answer:
f=open("d:\\a.txt","r")
for t in f.readlines():
for r in t.split():
print(r)
f.close()
32. Write a Program in python to count no. of words in a text file.
Answer:
f=open("d:\\a.txt","r")
c=0
for t in f.readlines():
for r in t.split():
c=c+1
print("no of words in file are ",c)
f.close()
33. Write a Program in python to show word with maximum length from a text file.
Answer:
f=open("d:\\a.txt","r")
lword=' '
for t in f.readlines():
for r in t.split():
if len(r)>len(lword):
lword=r
print("Maximum length word is:",lword)
f.close()
34. Write a Program in python to store list elements in a file and read these contents
from file again.

Answer:
days=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
f=open("d:\\b.txt","w")
for c in days:
f.write("%s\n"%c)
f.close()
f=open("d:\\b.txt","r")
for r in f.readlines():
print(r,end="")
f.close()
35. Write a Program in python to Copy the Contents of One File into Another.
Answer:
f=open("d:\\a.txt","r")
g=open("d:\\c.txt","w")
for line in f:
g.write(line)
f.close()
g.close()
print("file contents copied")
36. Write a Program in python to combine each line from first file with the
corresponding line in second file.
Answer:
f=open("d:\\a.txt","r")
g=open("d:\\b.txt","r")
for line1, line2 in zip(f, g):
print(line1+line2)
37. Write a Program in python to Search for a word ‘volatile’ in text file and print
part of the line.
Answer:
f=open("d:\\a.txt","r")
for line in f.readlines():
for part in line.split():
if "volatile" in part:
print(line)
f.close()
38. Write a Program in python to read character by character from a text file.
Answer:
file = open('d:\\a.txt', 'r')
while 1:
char = file.read(1) # read by character
if not char: break
print (char)
file.close()
39. Write a Program in python to convert file contents upper to lower and lower to
upper case in the same opened file.
Answer:
file = open('d:\\a.txt', 'rb+')
while 1:
char = file.read(1) # read by character
if not char: break
pos=file.tell()
file.seek(pos-1,0)
if char.isupper():
file.write(char.lower())
else:
file.write(char.upper())
file.close()
print("File contents upper to lower and lower to upper case converted")
40. What will be the output of the following Code Snippet?
fo = open("myfile.txt", "w+")
print ("File name is : ", fo.name)
seq="File handling is easy in python"
fo.writelines(seq)
fo.seek(14,0)
for line in fo:
print (line)
fo.close()

Answer:
File name is : myfile.txt
is easy in python
41. What will be the output of the following Code Snippet?
import sys
print ('Enter your name:')
name = ''
while True:
c = sys.stdin.read(1)
if c == '\n': break
name = name + c
print ('Entered name is:', name)

Answer:
Enter your name:
Student
Entered name is: Student
42. What will be the output of the following Code Snippet?
fo = open("a.txt", "w+")
print ("File name is : ", fo.name)
txt = "This is 1st line,"
fo.writelines( txt )
seq = " This is 2nd line, This is 3rd line"
fo.seek(0, 2)
fo.writelines( seq )
fo.seek(0,0)
line = fo.readlines()
print ("Read Line: %s" % (line))
fo.close()

Answer:
File name is : a.txt
Read Line: ['This is 1st line, This is 2nd line, This is 3rd line']

43. What is a text file?


Answer:
A text file is a file that contains printable characters and whitespace, organized into
lines separated by newline characters.

44. Name the methods which are commonly used to read data from a text file.
Answer:
read()
realine()
readlines()

45. Name the methods which are commonly used to write data into a text file.
Answer:
write()
writelines()

46. Write an appropriate statement to go to the beginning of a file at any time.


Answer:
fileobject.seek(0)

47. Differentiate between readline() and readlines() methods.


Answer:
The readline() method reads an entire line from the file whereas the readlines()
method reads the whole file contents at once and returns a list containing all the lines of
data in the file.
48. How is method write() different from writelines() in Python?
Answer:
The write() method writes any string to an open file whereas the writelines() method
writes a list of strings to a file.

49. Consider the following Code:

f = open(“mytry.", "w+")
f.write(“0123456789abcdef”)
f.seek(-3,2) //1
print(f.read(2)) //2

Explain statement 1 and give output of 2. (Board Que.)

Answer:
The statement 1 position the file object or set the current position at offset, i.e., 3 bytes
before the end of the file and 2 means move relative to end of the file.
The output of the statement 2 is: it reads 2 bytes before end of the file.
50. Name the Python Library modules which used to be imported to invoke the
following functions:
i)load()
ii) pow()

Answer:
i) pickle
ii) math

51. Observe the following code and answer the questions that follow:
(Board Que.)
file=open(“Mydata”, “a”)
_______________ # Blank1
file.close()

i) What type(text/binary) of file is Mydata?


ii) Fill the Blank1 with statement to write “ABC” in the file “Mydata”.

Answer:
i) Text file
ii) File.write(“ABC”)

52. Write a Python program to read a random line from a file.


Answer:
import random
def random_line(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
print(random_line('test.txt'))

53. Write a Python program to assess if a file is closed or not.


Answer:

f = open('abc.txt','r')
print(f.closed)
f.close()
print(f.closed)
54. Write a Python program that takes a text file as input and returns the number of
words of a given text file.
Answer:
def count_words(filepath):
with open(filepath) as f:
data = f.read()
return len(data.split(" "))
print(count_words(“test.txt"))
55. Write a user-defined function to read the content from a text file “Notes.txt” and
count & display the total number of lines and blank spaces present in it.
Answer:
import os
def countBlankSpaces():
txtfile="Notes.txt"
if os.path.isfile(txtfile):
fb=open(txtfile, 'r') #File is opened in read mode
bspace=nolines=0
print("File contents are:“)
while 1:
line=fb.readline() #Read a line
if not line:break
else:
print(line,end="")
nolines+=1 #Counts number lines read
#Strip off the new line character and any whitespace on the right
line=line.rstrip()
for i in line:
if i.isspace():
bspace+=1
print()
print("Total no of lines:%d"%nolines)
print("Total no of spaces:%d"%bspace)
fb.close()
else:
print("File does not exist.“)
56. Write Python program to Returns the index of the element with the maximum
value in a list.
Answer:
def max_element_index(arr):
return arr.index(max(arr))
print(max_element_index([2, 4, 8, 7, 10, 3, 0]))

57. Write Python program to reverse the content of a file and store it in another file.
Example:
Input: Hello Friends
for friends!
Output:
!sdneirf rof
sdneirF olleH
Answer:
f1 = open("output1.txt", "w")
with open("a.txt", "r") as myfile:
data = myfile.read()
data_1 = data[::-1]
f1.write(data_1)
f1.close()
58. Write a Python program to extract numbers from a text file and add them and
display its sum.
Answer:
file = open('number.txt', 'w')
data ='Python212 File342 handling1 878programs'
file.write(data)
file.close()
h = open('number.txt', 'r')
content = h.readlines()
a=0
for line in content:
for i in line:
if i.isdigit() == True:
a += int(i)
print("The sum is:", a)

59. Write a Python program to count number of lines in a text file.


Answer:
file = open("gfg.txt","r")
Count = 0
Content = file.read()
CoList = Content.split("\n")
for i in CoList:
if i:
Count += 1
print("Number of lines in the file:",Count)

60. Write a Python program to merge two files into a third file.
Answer:
data1 = data2 = “ "
# Reading data from file1
with open('file1.txt') as fp:
data1 = fp.read()
# Reading data from file2
with open('file2.txt') as fp:
data2 = fp.read()
# Merging 2 files
data1 += "\n"
data1 += data2
with open ('file3.txt', 'w') as fp:
fp.write(data1)

61. Write a Python program to delete a file.


Answer:
import os
print ("Enter 'quit' for exiting the program")
filename = input('Enter the file name to be deleted : ')
if filename == 'quit':
exit()
else:
print ('\nStarting the removal of the file !')
os.remove(filename)
print ('\nFile, ', filename, 'The file deletion is successfully completed')
62. Write a Python program to read contents of a file and copy only the content of
odd lines into new file.
Answer:
# open file in read mode
fn = open('demotext.txt', 'r')
# open other file in write mode
fn1 = open('nfile.txt', 'w')
# read the content of the file line by line
cont = fn.readlines()
type(cont)
for i in range(0, len(cont)):
if(i % 2 != 0):
fn1.write(cont[i])
else:
pass
# close the file
fn1.close()
# open file in read mode
fn1 = open('nfile.txt', 'r')
# read the content of the file
cont1 = fn1.read()
# print the content of the file
print(cont1)
# close all files
fn.close()
fn1.close()

63. Write a Python program to read a file word by word.


Answer:
# opening the text file
with open('GFG.txt','r') as file:
# reading each line
for line in file:
# reading each word
for word in line.split():
print(word)
64. Write a Python program to read character by character from a file.
Answer:
file = open('file.txt', 'r')
while 1:
# read by character
char = file.read(1)
if not char:
break
print(char)
file.close()

65. Write a Python program to read last N lines of a file.


Answer:
def LastNlines(fname, N):
# opening file using with() method so that file get closed after completing work
with open(fname) as file:
# loop to read iterate & last N lines and print it
for line in (file.readlines() [-N:]):
print(line, end ='')
# Driver Code:
if __name__ == '__main__':
fname = 'File1.txt'
N=3
try:
LastNlines(fname, N)
except:
print('File not found')
66. Write a Python program to get number of characters, words, spaces and lines in a file.
Answer:
def counter(fname):
num_words = 0
num_lines = 0
num_charc = 0
num_spaces = 0
# opening file using with() method so that file gets closed after completion of work
with open(fname, 'r') as f:
for line in f:
num_lines += 1
# declaring a variable word because every file is supposed to start with a word or a character
word = 'Y'
for letter in line:
if (letter != ' ' and word == 'Y'):
num_words += 1
word = 'N'
elif (letter == ' '):
num_spaces += 1
# assigning value Y to variable word because after white space a word is supposed to occur.
word = 'Y'
for i in letter:
if(i!=" " and i!="\n"):
num_charc += 1
print("Number of words in text file: ", num_words)
print("Number of lines in text file: ", num_lines)
print('Number of characters in text file: ', num_charc)
print('Number of spaces in text file: ', num_spaces)
# Driver Code:
if __name__ == '__main__':
fname = 'output1.txt'
try:
counter(fname)
except:
print('File not found')
Practice Question
67. A binary file “Tele.DAT” contains customer’s names and telephone numbers. Write
functions to do the following:
i) Append the records in the file.
ii) Display the name for a given telephone number. If the telephone number does
not exist then display error message: “Record not found”.

You might also like