psychology project日志
1. 将txt文件转换成excel格式,文件格式为:
2,4,"ON",4
0,0,0,1,0,0,2,0,30,3,0,30,4,1,60,5,0,60,6,0,30,7,0,30,8,0,0,9,0,0,10,0,0,11,0,0,12,0,0,13,0,0,14,0,0,15,0,0,16,0,0,17,0,0,18,0,0,19,0,0,20,0,0,21,0,0,22,0,0,23,0,0,24,0,0,25,0,0,26,0,0,27,0,0,28,0,0,29,0,0,30,0,0,31,0,0,32,0,0,33,0,0,34,0,0,35,0,0,36,0,0,37,0,0,38,0,0,39,0,0,40,0,0,41,0,0,42,0,0,43,0,0,44,0,0,45,0,0
需求为行与行之间用换行符分开,列于列之间用逗号分来,代码如下:
import xlwt wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet( 'Sheet1') #sheet页第一页 f = open('C:\\work\\psycology\\Samples\\fd72.1.txt', encoding='gbk') #.py文件和TestCase.txt同一目录,第一个参数是路径 row_excel = 0 #行 for line in f: line = line.strip('\n') #去掉换行符 line = line.split(',') #每一行以","分隔 print(line) #测试 col_excel = 0 #列 len_line = len(line) for j in range(len_line): print(line[j]) #测试 ws.write(row_excel, col_excel, line[j]) col_excel += 1 wb.save('C:\\work\\psycology\\Samples\\fd72.1.xls') #输出在同一目录 row_excel += 1 f.close
出现的报错为:PermissionError: [Errno 13] Permission denied
解决方案为:
1.检查对应路径下的文件是否存在,且被占用。如果文件不存在,就找到对应文件即可;如果文件存在,被占用,将占用程序暂时关闭。 2.修改cmd的权限,以管理员身份运行。 3.检查是否是打开了文件夹。
这里,关掉文件夹重新跑一次即可
2. 数出excel中一共有多少行
首先将xls保存成xlsx格式
from openpyxl import load_workbook wb = load_workbook(filename=r'C:/work/psycology/Samples/fd72.1.xlsx') ##读取路径 ws = wb.get_sheet_by_name("Sheet1") ##读取名字为Sheet1的sheet表 num = 1 while 1: cell = ws.cell(row=num, column=1).value if cell: num = num +1 else: print(num-1) break