Python Read/Write Csv File Example

CSV is the abbreviation of Comma Separated Values, CSV file is a text file contains CSV format content. Below is an example of CSV file content, it is so simple. We can see that there are three lines in the file, the first line is the header field name line, there are three fields. The second and the third line are related field content line.

'Name','Email','Title''jerry','[email protected]','CEO''tom','
  1. CSVFileOperator : This python class provide functions for csv file read / write operation. The two csv files in above picture are the result files this class write method created.
  2. TestCSVFileOperator : This is a python unittest.TestCase class which provide unit test for the CSVFileOperator methods. You can read Python 3 Unittest Html And Xml Report Example to learn more.

  3. run_all_test_case : This global function will run all test methods in the TestCSVFileOperator class.

  4. run_special_test_case(test) : This function will run the specified test method of TestCSVFileOperator class provided by the function parameter.

READ :   How To Connect MySQL Database In Django Project

CSVReadWriteExample.py

'''Created on Aug 24, [email protected]: zhaosong'''import csvimport unittestfrom csv import DictWriter# This is the csv file read/write class.class CSVFileOperator(object):    line_return_character = 'rn'    comma_separator = ','    # Write a data_list into a csv file identified by file_path.    # Each element in the data_list is also a list object represent one row.        def write_list_to_csv_file(self, data_list, file_path):        try:            file_object = open(file_path, 'w')            csv_file_writer = csv.writer(file_object, delimiter=",", quoting=csv.QUOTE_ALL, quotechar="'")            for item in data_list:                csv_file_writer.writerow(item)            print(file_path + " has been created successfully.")        except FileNotFoundError:            print(file_path + " not found.")    # Write a data_list into a csv file identified by file_path.    # Each element in the data_list is a dictionary object represent one row.        def write_dict_to_csv_file(self, data_list, column_name_list, file_path):        try:            file_object = open(file_path, 'w')            csv_dict_file_writer = csv.DictWriter(file_object, fieldnames=column_name_list)            csv_dict_file_writer.writeheader()            for item in data_list:                csv_dict_file_writer.writerow(item)                            print(file_path + " has been created successfully.")        except FileNotFoundError:            print(file_path + " not found.")    # Read csv file line by line and return the content.    def read_csv_file_by_reader(self, file_path):        ret = ''        try:          file_object = open(file_path, 'r')          csv_file_reader = csv.reader(file_object, delimiter=',')          row_number =           for row in csv_file_reader:              # Get one row list data string value,              # below code can avoid type convert error if column has number or boolean value.              row_str = ''              row_size = len(row)              for i in range(row_size):                  row_str += str(row[i]) + self.comma_separator              print("row_" + str(row_number) + " = " + row_str)              ret += row_str              ret += self.line_return_character              row_number += 1        except FileNotFoundError:            print(file_path + " not found.")        finally:          print("ret = " + ret)          return ret                             # Read csv file line by line and return the content.    def read_csv_file_by_dict_reader(self, file_path):        ret = ''        try:          file_object = open(file_path, 'r')          # csv.DictReader will return a dictionary list.          csv_file_dict_reader = csv.DictReader(file_object)          # Get csv file fields name list.          field_names = csv_file_dict_reader.fieldnames          # Get field name list size.          field_name_size = len(field_names)          # Get each field name.          for i in range(field_name_size):              field_name = field_names[i]              ret += field_name + self.comma_separator                    # Add line return character.               ret += self.line_return_character          print("Field Names : " + ret)          row_number =           # Each row is one dictionary.          for row in csv_file_dict_reader:              row_str = ''              # Loop the row field name.              for i in range(field_name_size):                  field_name = field_names[i]                  # Get field value in this row. Convert to string to avoid type convert error.                  row_str += str(row[field_name]) + self.comma_separator              print("row_" + str(row_number) + " = " + row_str)              ret += row_str              ret += self.line_return_character              row_number += 1        except FileNotFoundError:            print(file_path + " not found.")        finally:          print("ret = " + ret)          return ret         # This is the test case class for CSVFileOperator class.            class TestCSVFileOperator(unittest.TestCase):    # Test CSVFileOperator's write_list_to_csv_file.    def test_write_list_to_csv_file(self):        data_row_header = ['Name','Email','Title']        data_row_1 = ['jerry','[email protected]','CEO']        data_row_2 = ['tom','Python 3 Unittest Html And Xml Report Example
		
		
	
  • 0