If below two code snippets are giving same results then please let me know what is the advantage of using csv.reader
1)
import csv
f = open('a.csv', 'rb')
spamreader = csv.reader(f)
for a in spamreader:
print a
2)
f = open('a.csv', 'rb')
for a in f:
print a.split(',')
Result:
['SNO', ' Name', ' Dept']
['1', ' Def', ' Electronics']
['2', 'Abc', 'Computers']
In your example, I don't see an advantage of using the csv
module. However, things change when you have quoted elements:
SNO,Name,Dept
1,Def,Electronics
2,Abc,Computers
3,"here is the delimiter, in quotes",ghi
With the csv module, it is simply
import csv
with open('a.csv', 'rb') as f:
csv_reader = csv.reader(f, delimiter=',', quotechar='"')
for row in csv_reader:
print(row)
but splitting would ignore the quotes.
(Anyway, I recommend using pandas as shown here for reading CSV files. Please also note that you should close files you've opened. By using the with
statement, you can do it implicity.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments