CSV file: Comma-Separated Values, Chinese name, comma-separated value or character-separated value, its file store table data in the form of plain text. The file is a sequence of characters, which can consist of any number of records, separated by some kind of newline character. Each record is composed of fields, and the separator between fields is other characters or strings. All records have exactly the same sequence of fields, which is equivalent to the plain text form of a structured table.
CSV files can be opened with text files, Excel or similar and text files.
import csv #Need to import library
withopen('data.csv','w')as fp:
writer = csv.writer(fp)#Pass in the file handle first
writer.writerow(['id','name','age'])#Then write
writer.writerow(['10001','mike','20'])#Write by line
writer.writerow(['10002','Bob','22'])
writer.writerow(['10003','Jordan','21'])
import csv #Need to import library
withopen('data.csv','w')as fp:
writer = csv.writer(fp,delimiter ='*')#delimiter can only be a one-byte character
writer.writerow(['id','name','age'])#Then write
writer.writerow(['10001','mike','20'])#Write by line
writer.writerow(['10002','Bob','22'])
writer.writerow(['10003','Jordan','21'])
import csv
withopen('data.csv','w')as fp:
fieldnames =['id','name','age'] #First define the key in the dictionary
# Use DictWriter() method to add a fieldnames
writer = csv.DictWriter(fp,fieldnames = fieldnames,delimiter ='+')
writer.writeheader()#Write key first
# Write in the dictionary
writer.writerow({'id':'10001','name':'mike','age':'20'})
writer.writerow({'id':'10002','name':'Bob','age':'22'})
writer.writerow({'id':'10003','name':'Jordan','age':'21'})
import csv
withopen('data.csv','r',encoding ='utf8')as fp:
reader = csv.reader(fp)for row in reader:print(row)
import pandas as pd #Need to import pandas library
df = pd.read_csv('data.csv')print(df)
Recommended Posts