python提取包含特定字符串的行,Python,在Excel工作表中搜索列中的特定字符串,然后将这些行提取到文本文件中...

Here's the code I've frankensteined together from other posts,

import xlrd

import os.path

wb = xlrd.open_workbook(os.path.join('D:\Data','SPS1 demo data.xlsx'))

wb.sheet_names()

sh = #?

Strings=#variables

i = 1

file = open("Output.txt", "w")

while sh.cell(i,3).value = (Strings):

file.write(#row)

i = i + 1

file.close

It's not complete, but what I'm trying to accomplish is a search in column 3(or entire sheet, doesn't matter) for 5 specific strings and output those rows line by line to a text file, if possible csv formatted i.e. commas between each value.

How can I set a variable to 5 possible strings? Would this need to be an array?

I think the way that I have it written here will overwrite the text file each time rather than append it, is that correct? And if so what's the correct function, "file.append(#stuff)"?

解决方案

This should work. You can't assign 5 strings to a single variable, without using a list or some other data type. You can however check to see if the third cell's value (i[2] - here) is equal to any of the strings you're looking for ("string1" - "string5" - here).

import xlrd

sheet_data = []

wb = xlrd.open_workbook(Path_to_xlsx)

p = wb.sheet_names()

for y in p:

sh = wb.sheet_by_name(y)

for rownum in xrange(sh.nrows):

sheet_data.append((sh.row_values(rownum)))

found_list = []

rows_to_be_saved = []

for i in sheet_data:

if i[2] == "string1" or i[2] == "string2" or i[2] == "string3" or i[2] == "string4" or i[2] == "string5":

found_list.append(i)

else:

rows_to_be_saved.append(i)

text_file = open("Output.txt", "w")

text_file.write(found_list)

text_file.close()

Your output written to the text file "Output.txt" will be comma separated as the rows in your excel are read into python as tuples in a list.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值