Python 识别读取txt Execl CSV文件

coding=utf-8

1.txt读取
with open(“1233.txt”) as file:
for line in file:
print(line)

coding=utf-8

2.读取csv文件
import csv

csv_file = open(‘csvfile_input.csv’,‘r’)
reader=csv.reader(csv_file)
for item in reader:
print(item)

读取csv文件方式2

csvFile = open(“csvfile_input.csv”, “r”)
reader = csv.reader(csvFile) # 返回的是迭代类型
data = []
for item in reader:
print(item)
data.append(item)
print(data)
#csvFile.close()

从列表写入csv文件

csvFile2 = open(‘csvFile3.csv’, ‘w’, newline=’’) # 设置newline,否则两行之间会空一行
writer = csv.writer(csvFile2)
m = len(data)
for i in range(m):
writer.writerow(data[i])
csvFile2.close()

-- coding: utf-8 --

3.读取excel文件
import xlrd

from datetime import date,datetime

def read_excel():

ExcelFile=xlrd.open_workbook(r'E:\script\python-script\TestData.xlsx')

#获取目标EXCEL文件sheet名

print(ExcelFile.sheet_names())

#------------------------------------

#若有多个sheet,则需要指定读取目标sheet例如读取sheet2

#sheet2_name=ExcelFile.sheet_names()[1]

#------------------------------------

#获取sheet内容【1.根据sheet索引2.根据sheet名称】

#sheet=ExcelFile.sheet_by_index(1)

sheet=ExcelFile.sheet_by_name('TestCase002')

#打印sheet的名称,行数,列数

print(sheet.name,sheet.nrows,sheet.ncols)

#获取整行或者整列的值

rows=sheet.row_values(2)#第三行内容

cols=sheet.col_values(1)#第二列内容

print(cols,rows)

#获取单元格内容

print(sheet.cell(1,0).value.encode('utf-8'))

print(sheet.cell_value(1,0).encode('utf-8'))

print(sheet.row(1)[0].value.encode('utf-8'))

#打印单元格内容格式

print(sheet.cell(1,0).ctype)

if name == ‘main’:
read_excel()

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值