怎么用python读取txt文件里指定行的内容,并导入excel

如题所述

举个简单的例子,我这里有一个txt文件,文件中每一个row包含的是用户名和用户的身高,我们这里需要获取特定的行内容,比如身高大于170cm的内容,写入excel中。

data.txt

张三    172cm
李四    183cm
王五    166cm
赵六    159cm

孙乐乐   185cm
周熊熊   169cm
苏鹏鹏   176cm
吴刚刚   191cm
韩轩轩   172cm

sheet.py

'''
获取文件信息
'''
fi = open("data.txt")
lines = fi.readlines()
# 读取身高大于170cm
data = []
for human in lines:
    hinfo = human.split()
    if hinfo:
        if int(hinfo[1][:3]) >= 170:
            data.append(tuple(hinfo))

'''
写入excel
'''
import xlwt

# 创建workbook和sheet对象
workbook = xlwt.Workbook()  # Workbook的开头W 大写
sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True)
# 向sheet页中写入数据
sheet1.write(0, 0, '姓名')
sheet1.write(0, 1, '身高cm')
row = 1
for i in data:
    sheet1.write(row, 0, i[0])  # i0 姓名
    sheet1.write(row, 1, i[1])  # i1 身高
    row += 1

workbook.save('c.xlsx')  # 写入excel

执行sheet.py 后,打开同级目录下的c.xlsx

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-07-31
如果文件不大,建议使用下面的方法。由于linecache会缓存,所以对大文件可以使用自己简单是实现getline如下:
def getline(thefilepath, desired_line_number):
if desired_line_number < 1: return ''
for current_line_number, line in enumerate(open(thefilepath, 'rU')):
if current_line_number == desired_line_number - 1 : return line
return ''本回答被网友采纳
相似回答