

These lists are converted to a delimited string and written into the CSV file.Įxample 4: Writing multiple rows with writerows() In the above program, we have opened the file in writing mode. When we run the above program, a protagonist.csv file is created with the following content: SN,Movie,Protagonist With open('protagonist.csv', 'w', newline='') as file: Example 3: Write to a CSV file import csv This string can later be used to write into CSV files using the writerow() function. The csv.writer() function returns a writer object that converts the user's data into a delimited string. To write to a CSV file in Python, we can use the csv.writer() function. To learn more, visit: Reading CSV files in Python. The dialect parameter allows us to make the function more flexible. The complete syntax of the csv.reader() function is: csv.reader(csvfile, dialect='excel', **optional_parameters)Īs you can see from the syntax, we can also pass the dialect parameter to the csv.reader() function. Notice the optional parameter delimiter = '\t' in the above example. Reader = csv.reader(file, delimiter = '\t') Example 2: Read CSV file Having Tab Delimiter import csv To read such files, we can pass optional parameters to the csv.reader() function.

Suppose our CSV file was using tab as a delimiter. However, the function is much more customizable. In the above example, we are using the csv.reader() function in default mode for CSV files having comma delimiter. The reader object is then iterated using a for loop to print the contents of each row. Then, the csv.reader() is used to read the file, which returns an iterable reader object. To learn more about opening files in Python, visit: Python File Input/Output Here, we have opened the people.csv file in reading mode using: with open('people.csv', 'r') as file: Let's read this file using csv.reader(): Example 1: Read CSV Having Comma Delimiter import csv Suppose we have a csv file named people.csv in the current directory with the following entries. To read a CSV file in Python, we can use the csv.reader() function. While we could use the built-in open() function to work with CSV files in Python, there is a dedicated csv module that makes working with CSV files much easier.īefore we can use the methods to the csv module, we need to import the module first using: import csv txt) as long as their contents are in proper structure. Note: The csv module can also be used for other file extensions (like. You can have any single character as your delimiter as per your needs. If you open the above CSV file using a text editor such as sublime text, you will see: SN, Name, CityĪs you can see, the elements of a CSV file are separated by commas. To represent a CSV file, it must be saved with the. A CSV (Comma Separated Values) format is one of the most simple and common ways to store tabular data.
