python 内存数据库下载,Python 文件存储和数据库
Python 中數(shù)據(jù)存儲(chǔ)的方式和其他語(yǔ)言沒(méi)什么區(qū)別,主要分為兩個(gè)方面:文件存儲(chǔ)和數(shù)據(jù)庫(kù)存儲(chǔ)。
文件存儲(chǔ)
文件存儲(chǔ)的方法也分為很多種,主要包括:Python 內(nèi)置方法
NumPy 模塊方法
os 模塊方法
csv 模塊方法
Python 內(nèi)置方法
在不需要借助任何外界庫(kù)的前提下,python 內(nèi)置方法其實(shí)也可以完成我們需要的文件存取任務(wù):
open() 方法file object = open(file_name [, access_mode][, buffering])
該方法意義在于按照指定模式打開(kāi)文件,其中,各個(gè)參數(shù)的含義如下:file_name:file_name 變量是一個(gè)包含了你要訪問(wèn)的文件名稱(chēng)的字符串值。
access_mode:access_mode決定了打開(kāi)文件的模式:只讀,寫(xiě)入,追加等(可選,默認(rèn)為只讀)。
buffering: 如果 buffering 的值被設(shè)為 0,就不會(huì)有寄存。如果 buffering 的值取 1,訪問(wèn)文件時(shí)會(huì)寄存行。如果將 buffering 的值設(shè)為大于 1 的整數(shù),表明了這就是的寄存區(qū)的緩沖大小。如果取負(fù)值,寄存區(qū)的緩沖大小則為系統(tǒng)默認(rèn)。
簡(jiǎn)單示例:
12345#!/usr/bin/python
# -*- coding: UTF-8 -*-
file = open('tttt.py')
print(file.read())
這是一個(gè)最簡(jiǎn)單的讀取文件, 上面我們實(shí)際上使用的是一個(gè)相對(duì)路徑,當(dāng)然我們也可以使用絕對(duì)路徑:
12345#!/usr/bin/python
# -*- coding: UTF-8 -*-
file = open('C:\\Users\\Administrator\\Desktop\\tttt.py')
print(file.read())
我們常用 / 來(lái)表示相對(duì)路徑,\ 來(lái)表示絕對(duì)路徑,上面的路徑里 \\ 是轉(zhuǎn)義的意思。
接下來(lái)我們?cè)賮?lái)看看第二個(gè)參數(shù)如何使用,第二個(gè)參數(shù)是文件的打開(kāi)模式,可用的模式有如下幾個(gè):字符意義r讀取(默認(rèn))
w寫(xiě)入,并先截?cái)辔募?/p>
x排它性創(chuàng)建,如果文件已經(jīng)存在則失敗
a寫(xiě)入,如果文件存在則在末尾追加
b二進(jìn)制模式
t文本模式(默認(rèn))
+打開(kāi)用于更新(讀取與寫(xiě)入)
默認(rèn)模式為 r (打開(kāi)用于讀取文本,與 rt 同義)。 模式 w+ 與 w+b 將打開(kāi)文件并清空內(nèi)容。 模式 r+ 與 r+b 將打開(kāi)文件并不清空內(nèi)容。
值得注意的是,打開(kāi)一個(gè)文件的方式有兩種,一種是字節(jié)流的方式,另一種則是已經(jīng)編碼的字符方式,根據(jù)你的具體需要而定。
12345678910#!/usr/bin/python
# -*- coding: UTF-8 -*-
file = open('tttt.py', 'r+')
print(file.read())
file.write('dlc')
print(file.read())
file.close()
write() 方法可將任何字符串寫(xiě)入一個(gè)打開(kāi)的文件。該方法不會(huì)在字符串的結(jié)尾添加換行符 \n.
close() 方法刷新緩沖區(qū)里任何還沒(méi)寫(xiě)入的信息,并關(guān)閉該文件。
除了這個(gè)內(nèi)置函數(shù)外,Python 還有很多常用的內(nèi)置函數(shù):https://docs.python.org/zh-cn/3/library/functions.html#open
NumPy 模塊方法
NumPy 是使用 Python 進(jìn)行科學(xué)計(jì)算的基礎(chǔ)軟件包。除其他外,它包括:功能強(qiáng)大的N維數(shù)組對(duì)象。
精密廣播功能函數(shù)。
集成 C/C+ 和 Fortran 代碼的工具。
強(qiáng)大的線性代數(shù)、傅立葉變換和隨機(jī)數(shù)功能。
我們今天只關(guān)心它的一個(gè)特別的功能就是 I/O 操作,NumPy 可以讀寫(xiě)磁盤(pán)上的文本數(shù)據(jù)或二進(jìn)制數(shù)據(jù)。它有兩個(gè)相關(guān)函數(shù) load() 和 save().
123456789import numpy as np
a = np.array([1,2,3,4,5])
# 保存到 outfile.npy 文件上
np.save('outfile.npy',a)
# 保存到 outfile2.npy 文件上,如果文件路徑末尾沒(méi)有擴(kuò)展名 .npy,該擴(kuò)展名會(huì)被自動(dòng)加上
np.save('outfile2',a)
NumPy還有兩個(gè)常用的字符讀寫(xiě)方法 loadtxt() 和 savetxt():
12345678import numpy as np
a=np.arange(0,10,0.5).reshape(4,-1)
#改為保存為整數(shù),以逗號(hào)分隔
np.savetxt("a.txt",a,fmt="%d",delimiter=",")
#load時(shí)也要指定為逗號(hào)分隔
b = np.loadtxt("a.txt",delimiter=",")
print('b=\n',b)
os 模塊方法
Python 的 os 模塊封裝了常見(jiàn)的文件和目錄操作,官方文檔:https://docs.python.org/3/library/os.path.html
常用的方法如下:方法說(shuō)明os.mkdir創(chuàng)建目錄
os.rmdir刪除目錄
os.rename重命名
os.remove刪除文件
os.getcwd獲取當(dāng)前工作路徑
os.walk遍歷目錄
os.path.join連接目錄與文件名
os.path.split分割文件名與目錄
os.path.abspath獲取絕對(duì)路徑
os.path.dirname獲取路徑
os.path.basename獲取文件名或文件夾名
os.path.splitext分離文件名與擴(kuò)展名
os.path.isfile判斷給出的路徑是否是一個(gè)文件
os.path.isdir判斷給出的路徑是否是一個(gè)目錄
咱們著重看一下 os.write(fd, str) 方法和 os.read(fd,n):os.read(fd,n)
fd ? This is the file descriptor of the file(文件描述符).
n ? These are n bytes from file descriptor fd(讀幾個(gè)字節(jié)).
12345678910#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
file = os.open('tttt.py', os.O_RDWR | os.O_APPEND )
print(os.read(file, 10))
os.write(file, str.encode('dlc'))
print(os.read(file, 10))
os.close(file)
從這里我們其實(shí)可以看出,Python 內(nèi)置的 read() 和 write() 方法更適合具體的文件讀寫(xiě),而 os 模塊 更適合文件和目錄的操作,各有側(cè)重。
csv 模塊方法
CSV 是逗號(hào)分割值的文件格式,其文件以純文本的形式存儲(chǔ)表格數(shù)據(jù)。 CSV 文件的每一行都用換行符分割,列與列之間用逗號(hào)分割,它可以用 Excel 打開(kāi)。
例如我新建了一個(gè) Excel 內(nèi)容如下:
導(dǎo)出 csv 內(nèi)容如下:
使用 csv 模塊讀出數(shù)據(jù):
123456789#!/usr/bin/python
# -*- coding: UTF-8 -*-
import csv
with open('tttt.csv', 'r') as myFile:
lines = csv.reader(myFile)
for line in lines:
print(line)
這里使用到了 with 語(yǔ)句,詳細(xì)可參考:https://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/index.html
數(shù)據(jù)庫(kù)存儲(chǔ)
Python 標(biāo)準(zhǔn)數(shù)據(jù)庫(kù)接口為 Python DB-API,Python DB-API 為開(kāi)發(fā)人員提供了數(shù)據(jù)庫(kù)應(yīng)用編程接口。Python 數(shù)據(jù)庫(kù)接口支持非常多的數(shù)據(jù)庫(kù),你可以選擇適合你項(xiàng)目的數(shù)據(jù)庫(kù):GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
操作 MySQL
MySQLdb 是 python 操作 mysql 數(shù)據(jù)庫(kù)的一個(gè)庫(kù)。mysql 的幾乎所有的操作都可以實(shí)現(xiàn)。
安裝方法:
1pip install MySQL-python
mysqlclient 是 MySQLdb 的 fork 版,增加了對(duì) python 3.x 的支持和其它優(yōu)化,推薦替代 MySQLdb.
首先需要安裝 mysqlclient 庫(kù),連接 Python 和 MySQL. 本文出自水寒的博客:https://dp2px.com
1pip install mysqlclient
安裝完成后我們可以嘗試使用 Python 操作 MySQL,首先我們通過(guò) Navicat 創(chuàng)建一個(gè)數(shù)據(jù)庫(kù):
官方文檔地址:https://mysqlclient.readthedocs.io/
創(chuàng)建一個(gè)表,插入一條數(shù)據(jù):
1234567891011121314#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
conn = MySQLdb.connect(host='192.168.1.37', user='root', passwd='123456', db='lixiaoqiang')
cur = conn.cursor()
cur.execute("create table student(id int, name varchar(20), age varchar(10))")
cur.execute("insert into student values('1', 'XiaoMing', '18')")
cur.close()
conn.commit()
conn.close()
如果我們要更新這條數(shù)據(jù),可以使用如下 SQL:
1delete from student where id = 1;
假如我們要修改則使用如下 SQL:
1update student set age = '19' where id = 1;
當(dāng)然了,也可以使用占位符來(lái)插入數(shù)據(jù):
123456789import MySQLdb
conn = MySQLdb.connect(host='192.168.1.37', user='root', passwd='123456', db='lixiaoqiang')
cur = conn.cursor()
sql = "insert into student values(%s,%s,%s)"
cur.execute(sql, (2, 'XiaoHong', '20'))
cur.close()
conn.commit()
conn.close()
你也可以使用占位符的方式一次插入多條數(shù)據(jù),這個(gè)時(shí)候需要使用 executemany() 函數(shù),例如:
123456789101112131415161718#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
conn = MySQLdb.connect(host='192.168.1.37', user='root', passwd='123456', db='lixiaoqiang')
cur = conn.cursor()
sql = "insert into student values(%s,%s,%s)"
cur.executemany(sql, [
(3, 'Tom', '21'),
(4, 'Jack', '23'),
(5, 'Heiwa', '24'),
(6, 'xiaoM', '26'),
(7, 'Yahei', '28'),
])
cur.close()
conn.commit()
conn.close()
接下來(lái)我們來(lái)看看如何查詢表中的數(shù)據(jù),查詢數(shù)據(jù)需要使用 SQL 語(yǔ)句加 fetchone() 和 fetchmany() 函數(shù):
123456789101112131415#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
conn = MySQLdb.connect(host='192.168.1.37', user='root', passwd='123456', db='lixiaoqiang')
cur = conn.cursor()
cur.execute("select * from student")
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
cur.close()
conn.commit()
conn.close()
fetchone() 方法可以幫助我們獲得表中的數(shù)據(jù),可是每次執(zhí)行 cur.fetchone() 獲得的數(shù)據(jù)都不一樣,換句話說(shuō)我沒(méi)執(zhí)行一次,游標(biāo)會(huì)從表中的第一條數(shù)據(jù)移動(dòng)到下一條數(shù)據(jù)的位置,所以,我再次執(zhí)行的時(shí)候得到的是第二條數(shù)據(jù)。
scroll(0,'absolute') 方法可以將游標(biāo)定位到表中的第一條數(shù)據(jù)。還是沒(méi)解決我們想要的結(jié)果,如何獲得表中的多條數(shù)據(jù)并打印出來(lái)呢?
1234567891011121314#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
conn = MySQLdb.connect(host='192.168.1.37', user='root', passwd='123456', db='lixiaoqiang')
cur = conn.cursor()
allexe = cur.execute("select * from student")
info = cur.fetchmany(allexe)
for item in info:
print(item)
cur.close()
conn.commit()
conn.close()
操作 MongoDB
很多時(shí)候我們爬取的數(shù)據(jù)都是 JSON 格式的,這個(gè)時(shí)候使用非關(guān)系型數(shù)據(jù)庫(kù) MongeDB 就會(huì)方便很多,它是非常流行的 NoSQL 數(shù)據(jù)庫(kù)之一。
社區(qū)版是免費(fèi)的,下載地址:https://www.mongodb.com/download-center
注冊(cè)后去郵箱驗(yàn)證,然后登錄去下載,有兩個(gè)安裝包,一個(gè)是服務(wù)另一個(gè)是儀表盤(pán)。
先安裝好下面那個(gè)服務(wù)程序后會(huì)自動(dòng)啟動(dòng) mongodb 服務(wù),此時(shí)你可以選擇安裝圖形化儀表盤(pán)也可以不安裝,儀表盤(pán)如下:
創(chuàng)建一個(gè) Database 和一個(gè)表 student 如下:
緊接著我們使用 pymongo 來(lái)查詢這條數(shù)據(jù):
123456789101112#!/usr/bin/python
# -*- coding: UTF-8 -*-
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.testpython
collection = db.student
result = collection.find_one({'gender': 'man'})
print(result)
然后我們插入一條數(shù)據(jù),再查詢出所有數(shù)據(jù):
123456789101112131415#!/usr/bin/python
# -*- coding: UTF-8 -*-
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.testpython
collection = db.student
xiaogang = {"name": "xiaogang", "age": 20, "gender": "woman"}
collection.insert_one(xiaogang)
result = collection.find()
for item in result:
print(item)
還記得我們上一篇 《Python 的網(wǎng)絡(luò)請(qǐng)求 Requests 模塊使用》 的爬取豆瓣Top250 的案例嗎,我們接下來(lái)嘗試將爬取的數(shù)據(jù)存入 MongoDB 數(shù)據(jù)庫(kù):
12345678910111213141516171819202122232425262728293031323334353637383940414243#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests
from bs4 import BeautifulSoup
from pymongo import MongoClient
headers = {
'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
'Host': 'movie.douban.com'
}
def getMovieData():
movies = []
for i in range(0, 10):
link = 'https://movie.douban.com/top250?start=' + str(i * 25) + '&filter='
r = requests.get(link, headers=headers, timeout=3)
print("響應(yīng)狀態(tài)碼:", r.status_code)
soup = BeautifulSoup(r.text, "lxml")
div_list = soup.find_all('div', class_='item')
for each in div_list:
movieimg = each.find('div', class_='pic').a.img['src'].strip()
moviename = each.find('div', class_='hd').a.span.text.strip()
moviestar = each.find('span', class_='rating_num').text.strip()
movie = {'name': moviename, 'img': movieimg, 'star': moviestar}
movies.append(movie)
return movies
def insertDB(movies):
client = MongoClient('localhost', 27017)
db = client.testpython
collection = db.movie
collection.insert_many(movies)
movies = getMovieData()
print("爬取成功,開(kāi)始寫(xiě)入數(shù)據(jù)庫(kù)")
insertDB(movies)
print("寫(xiě)入數(shù)據(jù)庫(kù)成功")
總結(jié)
以上是生活随笔為你收集整理的python 内存数据库下载,Python 文件存储和数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 自动摘要php,修改DEDECMS文章自
- 下一篇: jsp iframe嵌入php,jsp嵌