Back to Browse

AWS | Project | Reading and Writing CSV Files in Python | Part-2

5.2K views
Sep 19, 2020
16:18

CSV (stands for comma separated values) format is a commonly used data format used by spreadsheets. The csv module in Python’s standard library presents classes and methods to perform read/write operations on CSV files. writer() This function in csv module returns a writer object that converts data into a delimited string and stores in a file object. The function needs a file object with write permission as a parameter. Every row written in the file issues a newline character. To prevent additional space between lines, newline parameter is set to ‘’. The writer class has following methods writerow() This function writes items in an iterable (list, tuple or string) ,separating them nby comma character. writerows() This function takes a list of iterables as parameter and writes each item as a comma separated line of items in the file. Following example shows use of write() function. First a file is opened in ‘w’ mode. This file is used to obtain writer object. Each tuple in list of tuples is then written to file using writerow() method. import csv # field names fields = ['empid', 'empname', 'empaddress'] # data rows of csv file rows = [{ "empid": "100", "empname": "vamsi", "empaddress": "ap" },{ "empid": "200", "empname": "krishna", "empaddress": "karnataka" }] with open('empdata.csv', 'w', newline='') as csvfile: fieldnames = ['empid', 'empname', 'empaddress'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) ######################################## import csv outputlist=[] with open('empdata.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['empid'], row['empname'],row['empaddress']) outputlist.append(row.values()) print(outputlist)

Download

1 formats

Video Formats

360pmp424.6 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

AWS | Project | Reading and Writing CSV Files in Python | Part-2 | NatokHD