python3读写excel操作

Python从json中提取数据

#json string:
s = json.loads('{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}')
print s
print s.keys()
print s["name"]
print s["type"]["name"]
print s["type"]["parameter"][1]

 

列表里的索引值

list = [5,6,7,9,1,4,3,2,10]

list.index(9)

同时可以返回列表中最大值的索引list.index(max(list))

最小值索引list.index(min(list))

 

xlrd读excel文件

workbook = xlrd.open_workbook("店铺坐标导入标准模板.xlsx")  # 打开excel文件
sheetname = workbook.sheet_names()  # 获取所有sheet表
sheet1 = workbook.sheet_by_name(sheetname[0])  # 获取表sheet1
sheet1.cell_value(3, 3) # 获取单元格的数据

cols = sheet1.col_values(0)  # 获取第1列内容,店铺名
location_excel = sheet1.col_values(3)  # 获取第4列内容,坐标
cols.remove(cols[0])  # 去除列表第一个数
del(cols[0])  # 去除列表第一个数
nrows = sheet1.nrows  # 获取表的行数
ncols = sheet1.ncols  # 获取表的行数
print(len(cols))


打开excel 
data = xlrd.open_workbook(‘test.xls’) #注意这里的workbook首字母是小写 
如果你打开的是含有较中文名的文件,请在程序首行加上:# -*- coding: utf-8 -*-

查看文件中包含sheet的名称 
data.sheet_names() 
得到第一个工作表,或者通过索引顺序 或 工作表名称 
table = data.sheets()[0] 
table = data.sheet_by_index(0) 
table = data.sheet_by_name(‘Sheet1’) 
获取行数和列数 
nrows = table.nrows 
ncols = table.ncols 
获取整行和整列的值(数组) 
table.row_values(i) 
table.col_values(i) 
循环行,得到索引的列表 
for rownum in range(table.nrows): 
print table.row_values(rownum) 
单元格 
cell_A1 = table.cell(0,0).value 
cell_C4 = table.cell(2,3).value 
分别使用行列索引 
cell_A1 = table.row(0)[0].value 
cell_A2 = table.col(1)[0].value

 

xlwt模块,可以创建一个excel文件 
workbook = xlwt.Workbook(encoding = ‘ascii’)#创建一个文件 
worksheet = workbook.add_sheet(‘My Worksheet’)#创建一个表 
worksheet.write(i, j, m)#向指定表中第i行j列写入数据m 
workbook.save(‘Mybook.xls’)#重要!,如果你要保存自己的文件,必须在程序结尾加上这条语句

 

xlwt读excel文件

import xlwt

#设置表格样式
def set_style(name,height,bold=False):
    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height
    style.font = font
    return style

#写Excel
def write_excel():
    f = xlwt.Workbook()
    sheet1 = f.add_sheet('学生',cell_overwrite_ok=True)
    row0 = ["姓名","年龄","出生日期","爱好"]
    colum0 = ["张三","李四","恋习Python","小明","小红","无名"]
    #写第一行
    for i in range(0,len(row0)):
        sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))
    #写第一列
    for i in range(0,len(colum0)):
        sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True))

    sheet1.write(1,3,'2006/12/12')
    sheet1.write_merge(6,6,1,3,'未知')#合并行单元格
    sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格
    sheet1.write_merge(4,5,3,3,'打篮球')

    f.save('test.xls')

 

 

读写txt操作

f = open('log.txt', 'a')  # 读写模式写a 这样就不会清空之前的log  # r w 读写模式
f.write("写log")
f.close()

读txt

f = open('/tmp/test.txt')
f.read()
'hello python!\nhello world!\n'
f.close()


f.readline()   逐行读取数据

f = open('/tmp/test.txt')
f.readline()
'hello girl!\n'
f.readline()
'hello boy!\n'
f.readline()
'hello man!'
f.readline()

 

f.readlines()   将文件内容以列表的形式存放,多行读取
f = open('/tmp/test.txt')
f.readlines()
['hello girl!\n', 'hello boy!\n', 'hello man!']
f.close()

 

Python 不会自动去掉换行符的。 
with open('test.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]

使用 strip()函数可以去掉行首和行尾的 whitespace,比如空格,制表符、换行符。

 

f.writelines()   多行写入

l = ['\nhello dear!','\nhello son!','\nhello baby!\n']
f = open('/tmp/test.txt','a')
f.writelines(l)
f.close()

f.next()   逐行读取数据,和f.readline() 相似,唯一不同的是,f.readline() 读取到最后如果没有数据会返回空,而f.next() 没读取到数据则会报错

f = open('/tmp/test.txt')
f.next()

 

替换
实例:把test.txt 中的hello全部换为"hi",并把结果保存到myhello.txt中。

#!/usr/bin/python
import re
f1 = open('/tmp/test.txt')
f2 = open('/tmp/myhello.txt','r+')
for s in f1.readlines():
f2.write(s.replace('hello','hi'))
f1.close()
f2.close()

 

排序读写脚本

f = open('cdays-4-test.txt')
result = list()
for line in f.readlines():                # 逐行读取数据
line = line.strip()                #去掉每行头尾空白
if not len(line) or line.startswith('#'):   # 判断是否是空行或注释行
continue                  #是的话,跳过不处理
result.append(line)              #保存
result.sort()                       #排序结果
print result
open('cdays-4-result.txt','w').write('%s' % '\n'.join(result))        #保存入结果文件

 

读写CSV文件

Python读取CSV文件
普通方法读取:

with open("fileName.csv") as file:
     for line in  file:
         print line
 

用CSV标准库读取:

import csv
csv_reader = csv.reader(open("fileName.csv"))
for row in csv_reader:
     print row
 

用pandas读取:
import pandas as pd
data = pd.read_csv("fileName.csv")
print data
data = pd.read_table("fileName.csv",sep=",")
print data

 

写入csv文件:


 #输出数据写入CSV文件
 import csv
 data = [
     ("Mike", "male", 24),
     ("Lee", "male", 26),
      ("Joy", "female", 22) ]
 
 #Python3.4以后的新方式,解决空行问题
with open('d://write.csv', 'w', newline='') as csv_file:
     csv_writer = csv.writer(csv_file)
     for list in data:
         print(list)
         csv_writer.writerow(list)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值