python檔案建立、讀取和寫入

aiee發表於2018-07-27
from selenium import webdriver
import xlrd
import xlwt
import os.path

filepath = "E:\\test.xls"
#檔案查詢,沒有就建立
file='test.xls'
if os.path.exists(filepath):
    print("找到檔案" + file)
else:
    print("沒有檔案%s,即將建立" % file)
    excel = xlwt.Workbook(encoding='utf-8') #建立一個新的工作簿
    table = excel.add_sheet('infor', cell_overwrite_ok=True) #新增一個sheet名為info
    excel.save(filepath)

#讀取表單資料
index = 0  # index表示表單
try:
    data = xlrd.open_workbook(filepath)
except Exception as e:
    print("檔案讀取異常")
table = data.sheet_by_index(index) # 讀取表單
nrows = table.nrows  # 行數
ncols = table.ncols  # 列數
colnames = table.row_values(0)  # 第一行資料
rolnames = table.col_values(0)  # 第一列資料
one = table.cell(0, 1).value  # 第一行第二列的值
print("行數%s, 列數%s, 第一行資料%s, 第一列資料%s, 第一行第二列的值%s" % (nrows, ncols, colnames, rolnames, one))

#檔案寫入

book = xlwt.Workbook(encoding='utf-8') #建立一個新的工作簿
sheet = book.add_sheet('data', cell_overwrite_ok=True)
sheet.write(0, 0, 'hello')
book.save('E:\\test1.xls')

相關文章