python读写数据文件

2020-01-27  本文已影响0人  小小孩儿的碎碎念

1. read、readline、readlines

(1)open函数
open('file','mode')
>>> with open('workfile') as f:
...     read_data = f.read()
>>> f.closed
True
(2)close方法
f = open(file) # 打开文件
f.close() # 关闭文件
(3)read方法
f.read(size) # f为文件对象

注:参数size(可选)为数字,表示从已打开文件中读取的字节计数,默认情况下为读取全部。

eg:假设有一个文件sample1.txt,内容如下:
This is python big data analysis!
现在读取该文件:

with  open('sample1.txt') as f:
content = f.read()
    print(content)
    f.close()

输出:
This is python big data analysis!

(4)readline方法
f.readline(size)

注:参数size表示从文件读取的字节数。

假设有一个文件sample2.txt,共三行,内容如下:
hello,my friends!
This is python big data analysis,
let's study.

要用readline函数读取该文件:

with  open('a.txt') as f:
    print(f.readline())
    print(f.readline(5))
    f.close()

输出:
hello,my friends!

This

(5)readlines方法

依旧以sample2.txt为例

with  open('a.txt') as f:
    print(f.readlines())
    f.close()

输出:
[ 'hello,my friends!\n,'This is python big data analysis,\n',''let's study.\n'']

(6)write方法
f.write([str]) # f为文件对象

参数[str]代表要写入的字符串
使用起来也很简单,比如将下面字符串
'hello,my friends!\nthis is python big data analysis'
写入到文件sample3.txt里

with  open('sample3.txt','w') as f:
    f.write('hello,my friends!\nthis is python big data analysis')
    f.close()

输出:
hello,my friends!
This is python big data analysis

2. 内置模块csv

import csv
with open('test.csv','r') as myFile:
    lines=csv.reader(myFile)
    for line in lines:
        print (line)
import csv
with open('test.csv','w+') as myFile:
    myWriter=csv.writer(myFile)
    myWriter.writerow([7,8,9])    # writerow一行一行写入
    myWriter.writerow([8,'h','f'])
    myList=[[1,2,3],[4,5,6]]    # writerows多行写入
    myWriter.writerows(myList)

3. numpy库

import numpy as np
np.loadtxt('test.csv',dtype=str)# loadtxt()中的dtype参数默认设置为float,这里设置为str字符串便于显示
import numpy as np
np.save('test.npy', np.array([[1, 2, 3], [4, 5, 6]]))# 先生成npy文件
np.load('test.npy')# 使用load加载npy文件
import numpy as np
x = np.arange(9).reshape(3,3)
x.tofile('test.bin')
np.fromfile('test.bin',dtype=np.int)

4. pandas库

import pandas as pd
pd.read_csv('test.csv')
import pandas as pd
pd.read_excel('test.xlsx')
df = pd.DataFrame([['a', 'b'], ['c', 'd']],index=['row 1', 'row 2'],columns=['col 1', 'col 2'])
j = df.to_json(orient='split')
pd.read_json(j,orient='split')

5、读写excel文件

python用于读写excel文件的库有很多,除了前面提到的pandas,还有xlrd、xlwt、openpyxl、xlwings等等

6. 操作数据库

python几乎支持对所有数据库的交互,连接数据库后,可以使用sql语句进行增删改查。

7、python连接MySQL数据库

(1)安装PyMySQL库

(2)安装MySQL数据库

(3)SQL基本语法

(4)连接数据库

#首先导入PyMySQL库
import pymysql
#连接数据库,创建连接对象connection
#连接对象作用是:连接数据库、发送数据库信息、处理回滚操作(查询中断时,数据库回到最初状态)、创建新的光标对象
connection = pymysql.connect(host = 'localhost' #host属性
                             user = 'root' #用户名
                             password = '******'  #此处填登录数据库的密码
                             db = 'mysql' #数据库名
                             )

(5)使用python代码操作MySQL数据库

#创建光标对象,一个连接可以有很多光标,一个光标跟踪一种数据状态。
#光标对象作用是:、创建、删除、写入、查询等等
cur = connection.cursor()
#查看有哪些数据库,通过cur.fetchall()获取查询所有结果
print(cur.fetchall())
#使用数据库test
cur.execute('USE test')
#在test数据库里创建表student,有name列和age列
cur.execute('CREATE TABLE student(name VARCHAR(20),age TINYINT(3))')
sql = 'INSERT INTO student (name,age) VALUES (%s,%s)'
cur.execute(sql,('XiaoMing',23))
cur.execute('SELECT * FROM student')
print(cur.fetchone())
#关闭连接对象,否则会导致连接泄漏,消耗数据库资源
connection.close()
#关闭光标
cur.close()

8、python连接Oracle数据库

(1)下载安装外包cx_Oracle,方式:在命令行输入 pip install cx_Oracle

(2)连接

conn = oracle.connect('username/password@host:port/sid')#分别填用户名/密码/数据库所在IP地址:port/sid

(3)获取光标对象curser

cur = conn.cursor()

(4)使用cursor进行各种操作

cur.execute(sql语句)

(5)关闭cursur、conn

cursor.close()
conn.close()

参考:
一文搞懂Python文件读写
n种方式教你用python读写excel等数据文件
python 连接各类主流数据库简单示例

上一篇 下一篇

猜你喜欢

热点阅读