Recently registered Kaggle account, practice a simple KNN algorithm for handwritten digital recognition. The downloaded training and test text is stored using a CSV file, so you can pick up the CSV module here.
The CSV full name (comma-separated values) is a format file, also known as a character split value. The records are split by newline characters, each record consists of fields, and the delimiters between fields are usually commas or tabs. Typically, all records have exactly the same field sequence.
When Python processes a CSV file, you can call the built-in module CSV.
Reader (CSVFile, dialect= ' Excel ', **fmtparams)
Parameters:
CSVFile, must be an object that supports iterations (Iterator), which can be a file object or a list object, or a file object that requires a "B" flag parameter when opened.
dialect, coding style, the default is the style of Excel, that is, separated by commas (,), dialect mode also supports customization, by calling the Register_dialect method to register.
Fmtparam, a format parameter used to override the encoding style specified by the previous dialect object.
# Coding:utf-8 Import CSV def read_csv (): With open ('read_csv.csv','r' as file: = csv.reader (file) for in lines: Print l
Read CSV
['ID','name']['1','a']['2','b']['3','C']['4','D']
Read Results
Writer (csvfile, dialect= ' Excel ', **fmtparams)
Parameters on the same
def Write_ CSV (): Result = [[5," e " ],[6, " f " ]" with open ( " write_csv.csv ", " WB " = Csv.writer (file) mywriter.writerow S (Result) Mywriter.writerow ([ 7, " g ])
Write a file
Note the time: The field read by default is a character type. Write files can be selected together with multiple records, or a single record, the record is expressed in sequence.
Python--csv file read/write