Python处理excel与txt文件

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

一、Python处理excel文件

1. 两个头文件

  1. import xlrd
  2. import xlwt

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

2. 读取excel文件

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

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

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

输出:Sheet2

  1. # 指定选择第二个sheet
  2. sheet1_content1 = workBook.sheet_by_index(1)
  3. # 获取第二个sheet中的 某一列 数据,index为 列 的编号
  4. content = sheet1_content1.col_values(index)
  5. 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 …]

  1. # 指定选择第二个sheet
  2. sheet1_content1 = workBook.sheet_by_index(1)
  3. # 获取第二个sheet中的 某一行 数据,index为 行 的编号
  4. content = sheet1_content1.row_values(index)
  5. 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文件

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

二、Python处理txt文件

1. 打开txt文件

  1. #方法1,这种方式使用后需要关闭文件
  2. f = open("data.txt","r")
  3. f.close()
  4. #方法2,使用文件后自动关闭文件
  5. with open('data.txt',"r") as f:

2. 读取txt文件

  1. # 读出文件,如果有count,则读出count个字节,如果不设count则读取整个文件。
  2. f.read([count])
  3. # 读出一行信息。
  4. f.readline()
  5. # 读出所有行,也就是读出整个文件的信息。
  6. f.readlines()

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

输出:1 2 3

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

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

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

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

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

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

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

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

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

相关文章