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()