CSV Format reading and writing
Comma separated values are sometimes referred to as character separated values because the separated characters can also be non commas. Separated files are called csv and separated files are called tsv
One thing to note: separator
import csv data=[] with open(r'data.csv',) as csvfile: file_list = csv.reader(csvfile,'mydialect') for line in file_list: data.append(line) print(data)
If the file is a different separator, such as \ n, you need to pass in the separator type.
import csv data=[] with open(r'data.csv',) as csvfile: file_list = csv.reader(csvfile,delimiter='\t') for line in file_list: data.append(line) print(data)
read
List mode read
import csv with open('data.csv','r',encoding='utf-8') as csvfile: reader = csv.reader(csvfile) for row in reader: # The contents read out are in list format print(row,type(row),row[1])
Dictionary reading
import csv with open('data.csv','r',encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile) for row in reader: # The read content is in dictionary format print(row['last_name'])
Write in
List mode write
import csv with open('data.csv','a+',encoding='utf-8',newline='') as csvfile: writer = csv.writer(csvfile) # Write to a row writer.writerow(['1','2','3','4','5','5','6']) # Write multiple rows writer.writerows([[0, 1, 3], [1, 2, 3], [2, 3, 4]])
Dictionary mode write
import csv with open('data.csv','a+',encoding='utf-8',newline='') as csvfile: filename = ['first_name','last_name'] # Write as column title writer = csv.DictWriter(csvfile,fieldnames=filename) writer.writeheader() writer.writerow({'first_name':'wl','last_name':'wtx'}) writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
json Format reading and writing
python's built-in json package provides four functions: dumps, dump, loads, and load. Responsible for the conversion of files and dictionaries without s. With s responsible for string and dictionary conversion.
Dictionary to string json.dumps(dict)
import json test_str = json.dumps({'name' : "cat"})
String to dictionary dict json.loads(string)
import json test_dict = json.loads("{'name' : "cat"}")
Dictionary to JSON file json.dump(dict, file)
import json with open("test.json","w") as f: json.dump({'name' : "cat"}, f)
JSON file to dictionary dict json.load(file)
import json with open("test.json",'r') as f: test_dict = json.load(f)