Python处理excel与txt文件

x33g5p2x  于2021-12-06 转载在 Python  
字(2.3k)|赞(0)|评价(0)|浏览(475)

一、Python处理excel文件

1. 两个头文件

import xlrd
import xlwt

其中xlrd模块实现对excel文件内容读取,xlwt模块实现对excel文件的写入。

2. 读取excel文件

# 打开excel文件
workBook = xlrd.open_workbook(excelPath)
# 获取所有的sheet的名字
allSheetNames = workBook.sheet_names()
print(allSheetNames)

输出:[‘Sheet1’, ‘Sheet2’]

# 按索引号获取sheet的名字(string类型)
sheet1Name = workBook.sheet_names()[1]
print(sheet1Name)

输出:Sheet2

# 指定选择第二个sheet
sheet1_content1 = workBook.sheet_by_index(1)  

# 获取第二个sheet中的 某一列 数据,index为 列 的编号
content = sheet1_content1.col_values(index)
print(content )

输出:[‘50_female_CNS’, 0.0001450627129261498, 0.00014610459059353443, 0.0001005863347657359, 6.582112999369104e-05, 0.00012061284774544405, ’ ', 0.00012075268247024065, 9.77776267815119e-05, 0.00012586155938565746, 0.0003279103274939261, 0.00022441965601437833 …]

# 指定选择第二个sheet
sheet1_content1 = workBook.sheet_by_index(1)  

# 获取第二个sheet中的 某一行 数据,index为 行 的编号
content = sheet1_content1.row_values(index)
print(content)

输出:[’’, 0.0001450627129261498, 0.00017014314076560212, 0.00018181811940739254, 0.0003775072437995825, 0.00042918333947459267, 0.0004889411346133797, 0.0001635510979069336, 0.00018714823789391146, 0.0002130216204564284, 0.0004294577819371397, 0.0004909460429236959, 0.0005394823288641913]

3. 写入excel文件

# 初始化写入环境
workbook = xlwt.Workbook(encoding='utf-8')
# 创建一个 sheet
worksheet = workbook.add_sheet('sheet')
# 调用 write 函数将内容写入到excel中, 注意需按照 行 列 内容 的顺序
worksheet.write(0, 0, label='car type')
worksheet.write(0, 1, label='50_female_CNS')
worksheet.write(0, 2, label='75_female_CNS')
worksheet.write(0, 3, label='95_female_CNS')

# 保存 excel
workbook.save("你的路径")

二、Python处理txt文件

1. 打开txt文件

#方法1,这种方式使用后需要关闭文件
f = open("data.txt","r")
f.close()

#方法2,使用文件后自动关闭文件
with open('data.txt',"r") as f:

2. 读取txt文件

# 读出文件,如果有count,则读出count个字节,如果不设count则读取整个文件。
f.read([count])  

# 读出一行信息。 
f.readline() 

# 读出所有行,也就是读出整个文件的信息。 
f.readlines()

f = open(r"F:\test.txt", "r")
print(f.read(5))
f.close()

输出:1 2 3

f = open(r"F:\test.txt", "r")
print(f.readline())
print(f.readline())
f.close()

输出
1 2 3 4 5
6,7,8,9,10

f = open(r"F:\test.txt", "r")
print(f.readlines())
f.close()

输出:[‘1 2 3 4 5\n’, ‘6,7,8,9,10\n’]

上述读取的格式均为:str 类型

3. 写入txt文件(需注意别清空了原来的内容)

首先指定待写入的文件,注意这里是 ‘w’

f = open(r'F:\test.txt','w')
f.write('hello world!')
f.close()

content = ['\nhello world1!','\nhello world2!','\nhello world3!\n']
f = open(r'F:\test.txt','w')
f.writelines(content)
f.close()

相关文章