csv
¶csv
module provides functions for working with CSV filescsv
module’s documentation recommends opening CSV files with the additional keyword argument newline=''
to ensure that newlines are processed properly import csv
with open('accounts.csv', mode='w', newline='') as accounts:
writer = csv.writer(accounts)
writer.writerow([100, 'Jones', 24.98])
writer.writerow([200, 'Doe', 345.67])
writer.writerow([300, 'White', 0.00])
writer.writerow([400, 'Stone', -42.16])
writer.writerow([500, 'Rich', 224.62])
.csv
file extension indicates a CSV-format filewriter
function returns an object that writes CSV data to the specified file objectwriter
’s writerow
method receives an iterable to store in the filewriterow
delimits values with commas, but you can specify custom delimiters!cat accounts.csv
writerow
calls above can be replaced with one writerows
call that outputs a comma-separated list of iterables representing the recordswriterow
encloses that string in double quotes to indicate a single valueaccounts.csv
and display the contents of each recordwith open('accounts.csv', 'r', newline='') as accounts:
print(f'{"Account":<10}{"Name":<10}{"Balance":>10}')
reader = csv.reader(accounts)
for record in reader:
account, name, balance = record
print(f'{account:<10}{name:<10}{balance:>10}')
csv
module’s reader
function returns an object that reads CSV-format data from the specified file objectreader
object one record of comma-delimited values at a time©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.