Python

Python 创建文件

#写入数据
file=open('a.txt','w',encoding='utf-8')
file.write("哈哈哈哈你好")
file.close()
#读取文件内容
file=open('a.txt','r',encoding='utf=8')
print(file.read())
file.close()

Python 对数据库进行操作--增删改查

#导包
import pymysql

class Shu():
#有参构造
    def __init__(self,id,name,price,author,publish):
        self.id=id
        self.name = name
        self.price = price
        self.author = author
        self.publish=publish
#无参构造
    def __init__(self):
        pass


con=pymysql.connect(host='127.0.0.1',user='root',password='123456',database='books')
#用于输送SQL语句执行对数据库的操作
cur=con.cursor()

# 增
# result=cur.execute("insert into book values(11,'哈哈哈','33','冯丽娟','北京出版社')")
# if result > 0:
#     print("插入成功")
# else:
#     print("插入失败")

# 删
# result=cur.execute("delete from book where id=4")
# print(result)

# 改
# result=cur.execute("update book set price=10 where price=20")
#
# if result > 0:
#     print("修改成功")
# else:
#     print("修改失败")

# 查
result=cur.execute("select * from book")
string=cur.fetchall()[0]#查询全部

shu =Shu()
shu.id=string[0]
shu.name=string[1]
shu.price=string[2]
shu.author=string[3]
shu.publish=string[4]
print(shu.id,shu.name,shu.price,shu.author,shu.publish)

Python 对csv进行操作

#python如何导入csv
import csv

with open('book.csv','r',encoding="utf-8") as file:
    #读取全部
    # vv=csv.reader(file)
    # for i in vv:
    #     print(i)

    #读取一列
    vv = csv.reader(file)
    for i in vv:
        print(i[1])   

Python 对Excle进行操作

import xlrd#导包

data=xlrd.open_workbook('book.xls')#将表 book.xls到处在桌面,xlrd中的open_workbook-取excel表格内容
print(data)#
sheet=data.sheets()[0]
hang=sheet.nrows#行数
print(hang)

lie=sheet.ncols#列数
print(lie)

#输出表格中所有横竖列的内容
for i in range(hang):
    for k in range(lie):
        print(sheet.cell(i,k))

你可能感兴趣的:(Python)