實(shí)際編程和面試都會(huì)遇到的典型問(wèn)題。
圖片來(lái)源于網(wǎng)絡(luò)
如何讀寫(xiě)文本文件
# python2
s = u'你好'
f = open('py2.txt','w')
f.write(s.encode('gbk'))
f.close()
f = open('py2.txt','r')
t = f.read()
f.close()
print t.decode('gbk')
# python3
f = open('py3.txt','wt',encoding='utf-8')
f.write('你好')
f.close()
f = open('py3.txt','rt',encoding='utf-8')
s = f.read()
f.close()
print(s)
如何設(shè)置文件的緩沖
# 全緩沖
# 默認(rèn)是4096
f = open('demo.txt','w',buffering=2048)
f.write('-' * 2048)
f.write('+')
# 行緩沖
f = open('demo1.txt','w',buffering=1)
# 無(wú)緩沖
f = open('demo2.txt','w',buffering=0)
如何訪(fǎng)問(wèn)文件的狀態(tài)
import os
import stat
#第一種 直接使用系統(tǒng)調(diào)用
# 1 文件的類(lèi)型
s = os.stat('demo.txt')
stat.S_ISDIR(s.st_mode)
stat.S_ISREG(s.st_mode)
# 2 文件的訪(fǎng)問(wèn)權(quán)限
s.st_mode & stat.S_IXUSR
# 3 文件的最后的訪(fǎng)問(wèn)/修改/節(jié)點(diǎn)狀態(tài)更改時(shí)間
import time
time.localtime(s.st_atime)
time.localtime(s.st_mtime)
time.localtime(s.st_ctime)
# 4 普通文件的大小
s.st_size
#第二種使用os.path下的函數(shù)
os.path.isdir('demo.txt')
os.path.isfile('demo.txt')
os.path.getatime
如何使用臨時(shí)文件
from tempfile import TemporaryFile,NamedTemporaryFile
f = TemporaryFile()
f.write(b'acvbnm'*100)
f.seek(0)
f.read(2)
ntf = NamedTemporaryFile()
ntf.name
如何讀寫(xiě)csv文件
from urllib.request import urlretrieve
# 下載平安銀行2017-04-01到2017-10-20的數(shù)據(jù)
#日期,股票代碼,名稱(chēng),收盤(pán)價(jià),最高價(jià),最低價(jià),開(kāi)盤(pán)價(jià),前收盤(pán),漲跌額,漲跌幅,換手率,成交量,成交金額,總市值,流通市值,成交筆數(shù)
urlretrieve('http://quotes.money.163.com/service/chddata.html?code=1000001&start=20170401&end=20171020','pingan.csv')
with open('pingan.csv','rt',encoding = 'gbk') as rf:
reader = csv.reader(rf)
with open('pingan_copy.csv','wt') as wf:
writer = csv.writer(wf)
headers = next(reader)
writer.writerow(headers)
for row in reader:
# 提取出2017-10-01后 成交額大于5000W的數(shù)據(jù)
if row[0] < '2017-10-01':
break
if round(float(row[12])) >= 50000000:
writer.writerow(row)
print('end')
如何讀寫(xiě)json文件
import json
import requests
url = 'http://wthrcdn.etouch.cn/weather_mini?city=北京'
response = requests.get(url)
# json.loads: str轉(zhuǎn)成dict
res = json.loads(response.content.decode('utf-8'))
type(res)
weather_forecast = res['data']['forecast'][0]
# json.dumps: dict轉(zhuǎn)成str
l = json.dumps(res)
type(l)
如何構(gòu)建并解析xml文件
from xml.etree.ElementTree import Element,ElementTree,tostring,parse
e = Element('collection')
e.set('shelf','New Arrivals')
e1 = Element('movie')
e1.set('title','Enemy Behind')
e11 = Element('type')
e11.text = 'War, Thriller'
e1.append(e11)
e.append(e1)
e2 = Element('movie')
e2.set('title','Enemy Behind')
e21 = Element('type')
e21.text = 'War, Thriller'
e2.append(e21)
e.append(e2)
e3 = Element('movie')
e3.set('title','Enemy Behind')
e31 = Element('type')
e31.text = 'War, Thriller'
e3.append(e31)
e.append(e3)
e4 = Element('movie')
e4.set('title','Enemy Behind')
e41 = Element('type')
e41.text = 'War, Thriller'
e4.append(e41)
e.append(e4)
et = ElementTree(e)
et.write('demo.xml')
f = open('demo.xml')
et = parse(f)
root = et.getroot()
# for child in root:
# print(child.get('title'))
#只能尋找當(dāng)前元素的直接子元素
root.find('movie[@title]')
root.findall('movie')
root.findall('movie[1]')
root.findall('movie[@title="Ishtar"]')
root.findall('movie[type="Comedy"]')
list(root.iter('movie'))
如何讀寫(xiě)excel文件
import xlrd,xlwt
# 讀
rbook = xlrd.open_workbook('demo.xlsx')
sheet = rbook.sheet_by_index(0)
# 列數(shù)
sheet.ncols
# 行數(shù)
sheet.nrows
# 單元格 cell
cell = sheet.cell(0,0)
# 返回一行
sheet.row(0)
sheet.row_values(1)
# 返回一列
sheet.col(0)
sheet.col_values(1)
# 寫(xiě)
wbook = xlwt.Workbook()
wsheet = wbook.add_sheet('sheet1')
# 寫(xiě)入cell
wsheet.write(0,0,'123')
wbook.save('output.xlsx')