0% found this document useful (0 votes)
25 views3 pages

CSV File Handling in Python

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)
25 views3 pages

CSV File Handling in Python

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

# PYTHON PROGRAM TO READ "STUDENT.

CSV" FILE CONTENTS

#PROGRAM 1

import csv
f=open("[Link]",'r')
csv_reader=[Link](f)
for row in csv_reader:
print(row)
[Link]()

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#PYTHON PROGRAM TO DEMONSTRATE USE OF OPEN ()


#PROGRAM 2

import csv
with open("[Link]",'r') as csv_file:
reader=[Link](csv_file)
rows=[] #list to store the file data
for rec in reader: #copy data into the list rows
[Link](rec)
print(rows)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#python program to count the number of records present in "[Link]" file


#PROGRAM 3
import csv
f=open("[Link]",'r')
csv_reader=[Link](f) #csv_reader is the csv reader object
c=0
for row in csv_reader:
c=c+1
print("no of records are" , c)
[Link]()

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#python program to print records in the form of comma separated values
#PROGRAM 4
import csv
f=open("[Link]",'r')
csv_reader=[Link](f)
for row in csv_reader:
print(','.join(row))
[Link]()

# JOIN() IS A STRING METHOD THAT JOINS ALL VALUES OF EACH ROW WITH COMMA SEPARATOR.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#python program to search records for given students name from csv file
#PROGRAM 5
import csv
f=open("[Link]",'r')
csv_reader=[Link](f)
name=input("enter the name to be searched ")
for row in csv_reader:
if(row[0]==name):
print(row)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

#program to write student data onto a csv file


#PROGRAM 6
import csv
fields=['NAME','CLASS','YEAR','%']
rows=[['REENA','XII','2005','92'],
['MEENU','XII','2006','94'],
['DEPAK','XII','2007','94'],
['SHWETA','XII','2008','95'],
['YAMINI','XII','2009','96'],
['SABA','XII','2010','95'],
['ASRA','XII','2011','93']]
#name of the csv file
filename='[Link]'

#writing to csv file

with open(filename,'w',newline='') as f:
#by default, new line is '\r\n'
#creating a csv writer object
csv_w=[Link](f,delimiter=',')
csv_w.writerow(fields)
for i in rows:
csv_w.writerow(i)
print("file created")

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#PROGRAM 7
#program to write student data onto a csv file

import csv
fields=['NAME','CLASS','YEAR','PERCENTAGE']

#DATA ROWS OF CSV FILE


rows=[
['HASSAN','XII','2007','89'],
['SEEMA','XII','2008','91'],
['SAMI','XII','2009','93'],
['RAHUL','XII','2010','94'],
['NIDHI','XII','2011','92'],
['HEENA','XII','2012','90'],
['NEETU','XII','2013','98'],
['ASNA','XII','2014','97'],
['MARYUM','XII','2015','96']]
#name of csv file
filename="[Link]"

with open(filename,'w',newline='') as f:
csv_w=[Link](f,delimiter=',')
#writing the fields once
csv_w.writerow(fields)
#writing the rows all at once
csv_w.writerows(rows)

print(" all rows written in one go")

Common questions

Powered by AI

The programs use the 'newline' parameter set to an empty string in 'with open' statements, which mitigates issues related to newline characters across different operating systems. This setup prevents Python from inserting additional newlines between rows, which can occur due to differing newline conventions (e.g., '\n' on Unix vs. '\r\n' on Windows), ensuring consistent output across platforms .

The 'join()' method is used to concatenate elements of an iterable, such as a list, into a single string with a specified separator between elements. In the context of printing CSV records, it joins each element of a row with a comma, effectively transforming a list of elements into a comma-separated string. This is particularly useful for converting internal data representations into CSV formatted strings .

When writing multiple rows to a CSV file using csv.writer, it is important to ensure that the file is opened in 'write' mode and a newline parameter is set to avoid double line breaks in Windows. Use the writerow() or writerows() methods effectively, depending on whether individual or multiple rows should be written at once. Additionally, ensure that the data is correctly formatted and adheres to the CSV structure, and manage field names that should align with data correctly .

The 'delimiter' parameter in csv.writer specifies the character used to separate fields in the output file. Setting a custom delimiter changes how fields are organized within a CSV file, affecting both readability and compatibility with other systems. For instance, changing the delimiter from a comma to a semicolon would alter the usual CSV format and could require adjustments when the file is accessed or processed by software expecting a specific delimiter .

The 'csv.reader' function in Python is used to iterate over lines in a CSV file. It reads each row of the open CSV file and returns it as a list, facilitating easy manipulation and examination of CSV data. This function handles the complexities of parsing lines into readable data fields derived from the CSV format .

Using 'with open' can be advantageous over 'open' because it ensures proper acquisition and release of resources. The 'with open' statement creates a context manager that automatically closes the file after the block of operations is executed, even if an error occurs. This minimizes the risk of keeping file handles open unintentionally, which can lead to memory leaks or file corruption .

Lists provide flexibility in CSV operations by allowing dynamic storage and manipulation of rows or columns of data. They enable easy appending, accessing, or modifying of elements, which can be crucial for interactions such as data updates, filtering based on conditions, or aggregating data before further processing or output formatting .

Closing a file after operations are complete is crucial because it frees up system resources and ensures that all buffers are flushed, thus preventing data corruption. Keeping a file open longer than necessary can lock the file, lead to memory leaks, or cause unexpected behavior in multi-threaded applications .

User input can be utilized to dynamically filter CSV content by comparing input values with CSV row elements. By prompting the user to enter a search key (e.g., a student's name), the program can iterate through each row of the CSV, checking for matches with the input. When a match is found, the relevant record can be displayed or further processed, thus making the program interactive and more versatile for specific data retrieval .

Omitting the writerow(fields) call would result in the CSV file lacking the header row, which can lead to difficulties in interpreting the data correctly. Including the headers helps clarify the data's structure, making it easier for both humans and software interpreting the CSV to understand what each column represents. Headers act as labels and are often necessary for conducting operations such as sorting, filtering, or visualizing the data .

You might also like