【发布时间】:2022-01-07 16:54:02
【问题描述】:
我正在尝试执行一个脚本,该脚本将解压缩包含多个 txt 和 .csv 文件的压缩文件夹中的所有文件,仅在 .csv 文件中搜索字符串,如果它包含该字符串,则复制整个压缩文件夹到一个新文件夹,如果没有,请转到下一个压缩文件夹。我有几个脚本可以完成其中的一部分,但无法将它们拼凑在一起。我是python的初学者,所以这个脚本看起来很复杂。
这个脚本打印压缩文件夹中的文件,我的下一步是在它包含的 .csv 文件中搜索字符串 PROGRAM 但我不知道如何编码,我想它在最后这段代码,因为它看起来像是在循环中运行。
import os
import pandas as pd
import zipfile
curDir = os.getcwd()
zf = zipfile.ZipFile(curDir + '\namedfile.zip')
text_files = zf.infolist()
list_ = []
print ("Uncompressing and reading data... ")
for text_file in text_files:
print(text_file.filename)
我单独编写了这个脚本,在包含 .csv 文件的文件夹中搜索字符串 PROGRAM
import os
from pathlib import Path
#Searches the .csv files within the "AllCSVFiles"
#folder for the string "GBSD"
search_path = "./AllCSVFiles"
file_type = ".csv"
search_str = "PROGRAM"
if not (search_path.endswith("/") or search_path.endswith("\\") ):
search_path = search_path + "/"
if not os.path.exists(search_path):
search_path ="."
for fname in os.listdir(path=search_path):
if fname.endswith(file_type):
fo = open(search_path + fname)
line = fo.readline()
line_no = 1
while line != '' :
index = line.find(search_str)
if ( index != -1) :
print(fname, "[", line_no, ",", index, "] ", sep="")
line = fo.readline()
line_no += 1
fo.close()
有没有更简单的方法来处理这段代码?
【问题讨论】:
-
嗨,您也许可以使用zipgrep 或在循环结束时在匹配时复制文件夹。也许将这些方法组合到一个类中,以便更容易执行该过程。
标签: python pandas csv search script