Exchanging data between different platforms 1, the frame, the language
Since .txt files do not have the semantic tags, not suitable for the format of data exchanged between different platforms, frames and languages.
Different platforms, the exchange of data between frame formats and languages: CSV, TSV, json etc.
2 CSV file
Read and write 2.1 CSV files do not need to download additional libraries, the system comes
2.2 to read data
Import module
import csv
Read data
with open(‘C:\\data.csv’,encoding=’utf8’) as f:
reader=csv.reader(f)
NOTE: After reading the file, using the next () method reads the first column, and then use the cycle in which data is read
v_lietou=next(reader)
NOTE: use namedtuple column head and the corresponding values:
ROW=namedtuple(‘ROW’,v_lietou)
Then for any one line:
line=ROW(*line)
Note: CSV file directly supports reading way dictionary table:
with open(‘C:\\data.csv’,encoding=’utf8’) as f:
reader=csv.DictReader(f)
2.3 write data
Import module
import csv
data input
headers=[‘name’,’dep’,’sal’] val=[(‘tom’,’dev’,600),(‘peter’,’pro’,300),(‘jim’,’che’,500)] with open(‘C:\\data.csv’,’w’,encoding=’utf8’) as f: writer=csv.writer(f) writer.writerow(headers) writer.writerows(val)
Note: write a single line is writerow, write multiple lines are writerows
Note: CSV files can also support writing dictionary tables
with open(‘C:\\data.csv’,’w’,encoding=’utf8’) as f: writer=csv.DictWriter(f,headers) writer.writeheader() writer.writerows(val)
3 json file
json format similar table and dictionary
json is True, False, Null are lowercase
3.1 json string read
Import module
Import JSON Data = { ' name ' : ' Tom ' , ' DEP ' : ' dev ' , ' SAL ' : 6000}
Dictionary converted into json format
= json_data json.dumps (Data)
converted into a dictionary format json
DATAl = json.loads (json_data)
3.2 json file to read and write
Write the file: json.dump (data, file name)
with open('data.json','w',encoding='utf-8') as f: json.dump(data,f)
Read the file: json.load (filename)
with open('data.json','r',encoding='utf-8') as f: data=json.load(f) print(data)
4 excel file read
Read and write Excel files without their own library, you need to install xlrd
The main methods are:
Open File: book = xlrd.open_workbook (file)
Acquire table: sheet = book.sheet_by_index (0) or book.sheet_by_name (name)
Get the number of rows in the table: num_row = sheet.nrows
Obtaining i-th row data: data = sheet.row_values (i)