Python,在excel工作表中搜索列中的特定字符串,并将这些行提取到文本fi

2024-04-23 10:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在其他帖子里一起编造的密码

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

它还没有完成,但我要完成的是在第3列(或整个工作表,无所谓)搜索5个特定字符串,并逐行输出到文本文件,如果可能的话,csv格式,即每个值之间的逗号。

如何将变量设置为5个可能的字符串?这需要一个数组吗?
我认为我在这里写的方法每次都会覆盖文本文件,而不是附加它,对吗?如果是,那么正确的函数是什么,“file.append(#stuff)”?


Tags: path字符串import密码osshopen帖子
1条回答
网友
1楼 · 发布于 2024-04-23 10:46:33

这应该管用。如果不使用列表或其他数据类型,则不能为单个变量指定5个字符串。但是,您可以检查第三个单元格的值(i[2]-这里)是否等于您要查找的任何字符串(“string1”-“string5”-这里)。

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()

当excel中的行作为列表中的元组读入python时,写入文本文件“output.txt”的输出将以逗号分隔。

相关问题 更多 >