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

Python CSV File Handling Guide

The document provides a comprehensive guide on how to work with CSV files in Python using the csv module, including importing the module, reading from CSV files with the reader() function, and writing to CSV files with the writerow() function. It includes code examples for reading data, displaying it in a formatted way, and inserting both single and multiple rows into a CSV file while addressing common issues like avoiding blank rows. The document emphasizes the importance of proper file handling and user input for data entry.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Python CSV File Handling Guide

The document provides a comprehensive guide on how to work with CSV files in Python using the csv module, including importing the module, reading from CSV files with the reader() function, and writing to CSV files with the writerow() function. It includes code examples for reading data, displaying it in a formatted way, and inserting both single and multiple rows into a CSV file while addressing common issues like avoiding blank rows. The document emphasizes the importance of proper file handling and user input for data entry.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CSV Files in Python – Import CSV, Open, Close csv, read-write csv using [Link] and csv.

writerow
import csv module
To import csv module we can use any one of the following syntax:
import csv
from csv import writerow
from csv import writerow, reader
from csv import *
In above statements, first example is used to import the complete csv module therefore we can
access anything from the module using csv and .(dot) symbol.
In second syntax it won’t access the complete code, it will just allow to use writerow() function only
in the program. In next part two functions used from the module and last all the classes, functions
and variables can be access using *.
Note: To save the memory and reduce the program size third syntax can be used for project with a
number of required functions only.

The reader() function


The reader() function is used to read the data from CSV file. The syntax of reader() function is as
following:
[Link](csvfile, dialect=’excel’, **fmtparams)
Where
csvfile – is the path of CSV file which is going to be read.
dialect – It is used to set a specific parameters like delimiter, single/double quotes or a space
**fmtparams – These are keyword arguments and can be used as per the need of the program
Code to read data from CSV file:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
data = list(dt)
[Link]()
print(data)
f_CSVread()
Explanation:
In the above code, I have created one CSV file named [Link].
Line 1: As we are going to read data only therefore we have written the import statement with from
csv import reader statement.
Line 2: It is a function header defines a function f_CSVread().
Line 3: f is defined as file object to open the CSV file with “r” mode.
Line 4: In this line dt is an object which stores data in from CSV file using reader() function.
Line 5: By default read() function returns object from CSV file not the actual data. So actual data is
stored in data named list object using list() conversion method.
Line 6: This statement close the file to avoid any conflict in future.
Line 7: This statement prints the output eventually.
Line 8: The function is called to execute the program.
Output:
Code to display data in proper format:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
data = list(dt)
[Link]()
for i in data:
print(i)
f_CSVread()
To print the data in proper format for loop can be used. In the above code, we have used for loop
and traverse data from the list.
Output

Here the output is displayed according to the list. To get it more clear and concise format we have to
use another for loop to traverse the values separately. Check following code:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
data = list(dt)
[Link]()
for i in data:
for j in i:
print('\t|',j,end=" ")
print()
f_CSVread()
In the above code we have used nested loop to print each value separately from the list and
formatted using ‘\t\‘ hence the output looks like as following:

Displaying output without list object


In the below-given code where list object is not used to store data read from CSV file:
from csv import reader
def f_CSVread():
f = open("[Link]","r")
dt = reader(f)
for i in dt:
for j in i:
print('\t|',j,end="")
print()
[Link]()
f_CSVread()
The writerow() function
The writerow() function is used to write data in CSV file.
Creating header row and CSV file
When we are writing data into CSV file we have to create a header row first. Follow the below given
steps to write a header row.
Check the following code which creates a CSV file and creates one object to write a header row in
CSV file. Here we have used writer() function to feed data and writerow() function to insert values
into a row.
from csv import writer
def f_CSVwrite():
f = open("[Link]","w")
dt = writer(f)
[Link](['Rank','Batsman','Team','Rating'])
[Link]()
f_CSVwrite()

Inserting data into CSV file


We can insert single row or multiple rows together in CSV file. Let’s have a look at both.
Insert a single row at a time
If we have already created a header row then we have to use append mode to insert data. Observe
the following code:
from csv import writer
def f_CSVwrite():
f = open("[Link]","a")
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
dt = writer(f)
[Link]([r,b,t,rt])
print("Record has been added.")
[Link]()
f_CSVwrite()
Input through Python interpreter
entry for inserting record into csv thorugh python
Data stored in CSV

Insert multiple rows at a time


To insert multiple rows use while loop inside the function and use validation to stop the input by the
user. For validation, we have used a string variable to check user want to restrict the data entry or
want to continue. Observe the following code we have done the same.
from csv import writer
def f_CSVwrite():
f = open("[Link]","a")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
[Link]([r,b,t,rt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = [Link]()
if ch=="YES":
print("*************************")
else:
break
[Link]()
f_CSVwrite()
Python interpreter screen
Inserting data into CSV
Data stored in CSV

Data into csv through python


Now when we insert a row using this method it will add a blank row by default before each new
record. We can specify the newline character into an open function to avoid this. To solve this
problem we have used the following code:
from csv import writer
def f_CSVwrite():
f = open("[Link]","a",newline="\n")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
[Link]([r,b,t,rt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = [Link]()
if ch=="YES":
print("*************************")
else:
break
[Link]()
f_CSVwrite()
Python interpreter input
Avoid blank row in CSV
Output in CSV File

CSV data without blank rows

Common questions

Powered by AI

Reading a CSV file typically involves using `csv.reader` to parse and extract data into Python objects, handling it line by line or converting it to lists for processing . Writing, however, involves `csv.writer` to format and push data into a file from a list or sequence, requiring file mode 'w' for new files or 'a' for appending. Writing can require format adjustments such as newline handling to prevent blank lines, which isn't necessary in reading operations .

The 'dialect' parameter in `csv.reader` is used to define a set of specific formatting parameters such as delimiter, quote character, and escape character which apply to the CSV file being read. This allows for customization of how different CSV formats are handled during the read operation .

The `writerow` function is used to write a single row of data to a CSV file. It formats the given data into a comma-separated line and appends it to the file, creating the CSV structure .

Using `from csv import *` imports all functions and classes from the CSV module into the current namespace. This can lead to memory inefficiency and increased file size in the case of larger modules. It also increases the risk of naming conflicts, making code maintenance more difficult, as identifying where functions come from becomes less clear .

Using `f.close()` ensures that the file is properly closed after operations, which helps in avoiding potential data corruption or conflicts when the file is accessed later . Proper file closure also frees up system resources associated with file handling .

Using a nested loop allows iterating through each element in a list of lists, enabling the separation of individual data points for better formatting. This approach provides clearer outputs, such as aligning data into columns or adding specific delimiters, making the data easier to read .

Using `import csv` imports the entire csv module, allowing access to all functions and classes with the `csv.` prefix . In contrast, `from csv import writer` imports only the `writer` function, allowing direct use of `writer` without the `csv.` prefix .

To avoid adding blank rows when writing to a CSV file, specify the newline character in the open function by using `newline=""` .

Open the CSV file in append mode using `open('file.csv', 'a')`. Use a loop to continuously prompt the user to input data fields (rank, batsman name, team, rating). Use `writerow()` to append each record to the file. After each entry, ask the user if they want to add more records. Validate the input by checking if the user enters 'YES'. If not, exit the loop, and use `f.close()` to close the file .

Converting CSV data to a list enables easier manipulation and access to the data elements in Python. List structures allow for indexing, slicing, and iteration, making them versatile for data processing tasks compared to the iterator object returned by `reader` .

You might also like