近來自學python,今天寫了一段小代碼對文件進行操作。
python的安裝,我是安裝了anaconda,從清華鏡像下載的,地址 https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/。
python對excel進行操作,需要導入包xlrd,用pip install xlrd即可。
代碼:
1 import xlrd 2 3 def strs(row): 4 values = ""; 5 for i in range(len(row)): 6 if i == len(row) - 1: 7 values = values + str(row[i]) 8 else: 9 values = values + str(row[i]) + "," 10 return values 11 12 # 打卡文件 13 data = xlrd.open_workbook("2.xls") 14 sqlfile = open("1.txt", "a") # 文件讀寫方式是追加 15 16 table = data.sheets()[0] # 表頭 17 nrows = table.nrows # 行數 18 ncols = table.ncols # 列數 19 colnames = table.row_values(0) # 某一行數據 20 # 打印出行數列數 21 print(nrows) 22 print(ncols) 23 print(colnames) 24 for ronum in range(1, nrows): 25 row = table.row_values(ronum) 26 values = strs(row) # 條用函數,將行數據拼接成字符串 27 28 sqlfile.writelines(values + "\r") #將字符串寫入新文件 29 sqlfile.close() # 關閉寫入的文件