數(shù)據(jù)編碼與處理
如何讀寫csv文件
?可以使用標準庫中的csv模塊,完成csv 文件讀寫
from urllib import urlretrieve urlretrieve('http://table.finance.yahoo.com/table.csv?s=000001.sz','pinan.csv') ?#請求的數(shù)據(jù)保存道csv文件 rf = open('pinan.csv','rb') ?# 打開文件 import csv re = csv.reader(rf) # 得到一個迭代器 print(re.next()) # 得到第一行數(shù)據(jù) # 寫的情況 wf = open("pinan.csv",'wb') we = csv.writer(wf) we.writerow([]) # 寫入一行 we.flush() # 刷新
?
?如何讀寫json數(shù)據(jù)
使用json模塊中的loads,dumps函數(shù)來完成json數(shù)據(jù)讀寫
requests 模塊進行網(wǎng)頁數(shù)據(jù)的請求
import json l = [1,2,'qwer'] l2 = json.dumps(l) # 把字符串轉為json格式 json.dumps(l,separators=[',',';']) #加分割符 json.dumps(l,sort_keys=True) #加排序 # json轉為字符串 json.loads(l2) # load,dump ?與加s的功能一樣只是接口不一樣, 他對接一個文件 # 如寫到文件中 with open("f1.json",'wb') as f: ? ?json.dump(l,f) ? # 寫到文件
?
在python中如何解析xml文檔
使用from xml.etree import ElementTree 中的parse函數(shù)
from xml.etree import ElementTree f = open('Boot1.html') et = ElementTree.parse(f) ?# 解析 root = et.getroot() # 得到根節(jié)點 , root是其中的一個元素對象 root.tag # 查看標簽 root.attrib #查看屬性 root.get('name') # 查看name屬性 root.text root.getchildren() # 獲取子元素 得到一個列表 root.find("country") # 找到標簽名是country的 找打第一個 root.findall('country') # 找到所有的country子元素返回一個列表 root.iterfind('country') # 找到所有的返回一個可迭代對象 root.iter('rank') # 遞歸的尋找標簽是rank的子標簽 root.findall('country[@name]') #找到country子元素含name屬性的 root.findall('country[rank=5]')# 在到country下子標簽rank的值為5
構建xml 文檔
使用from xml.etree import ElementTree 中的 write方法寫入
from xml.etree.ElementTree import Element,ElementTree e = Element("Data") ?# 一個標簽 e.set('name','abc') # 設置屬性 e.text = '123' ? # 設置值 e2 = Element("open") ?# 這只一個標簽 e2.text = "xiao"e.append(e2) # e2 標為e的子標簽from xml.etree.ElementTree import tostring # 看到轉后格式 print(tostring(e)) # 結果b'<Data name="abc">123</Data>'et = ElementTree(e) # 準備寫道文件中 et.write("xiao.xml")
?
如何讀寫excel文件
使用第三方庫xlrd 與xlwt 完成excel 的讀寫
import xlrd # 讀取表 boak = xlrd.open_workbook('demo.xlsx') # 打開一張表 boak.sheets() # 獲取這個文件中的所有張表 sheet = boak.sheet_by_index(0) #得到第一張表 sheet.nrows() # 表的行數(shù) sheet.ncols() # 表的列數(shù) cell = sheet.cell(0,0) # 獲取第一個單元格 cell.ctype() #內(nèi)容類型 1 表示文本, 2 表示數(shù)字 者的數(shù)字是根據(jù)這個來的 xlrd.XL_CELL_TEXT cell.value() # 查看這個單元格值 sheet.row(1) # 返回第一行返會一個列表 sheet.row_values(1) #直接取第一行值 sheet.row_values(1,start_colx=1,end_colx=5) # 取值指定從第二列開始取, 結束到 # 給行添加一個cell , 第一行第5列, 類型文本, 值 xiao sheet.put_cell(1,5,1,'xiao',None)
寫
import xlwt wbook = xlwt.Workbook() # 創(chuàng)建一個book出來就xecel 文件 wsheet = wbook.add_sheet("test") #添加表名字test wsheet.write(1,2,2,5)# 添加值在1行5列 類型2 值為5 wsheet.save("file.xlsx") #保存到文件
原文:https://www.dianjilingqu.com/440612.html