Python 如何在excel电子表格目录中搜索字符串并使其返回文件名?
下面是我目前拥有的——这是我在其他论坛上看到的东西的组合 所有Excel电子表格都有相同的格式,我要查找的字符串总是在B列中 理想情况下,如果我能搜索一个字符串并让它返回文件名,我会很高兴Python 如何在excel电子表格目录中搜索字符串并使其返回文件名?,python,excel,search,Python,Excel,Search,下面是我目前拥有的——这是我在其他论坛上看到的东西的组合 所有Excel电子表格都有相同的格式,我要查找的字符串总是在B列中 理想情况下,如果我能搜索一个字符串并让它返回文件名,我会很高兴 import os keyword = input("Search For?: ") # ask the user for keyword, use raw_input() on Python 2.x root_dir = "DIRECTORY" # path
import os
keyword = input("Search For?: ") # ask the user for keyword, use raw_input() on Python 2.x
root_dir = "DIRECTORY" # path to the root directory to search
for root, dirs, files in os.walk(root_dir, onerror=None): # walk the root dir
for filename in files: # iterate over the files in the current dir
file_path = os.path.join(root, filename) # build the file path
try:
with open(file_path, "rb") as f: # open the file for reading
# read the file line by line
for line in f: # use: for i, line in enumerate(f) if you need line numbers
try:
line = line.decode("utf-8") # try to decode the contents to utf-8
except ValueError: # decoding failed, skip the line
continue
if keyword in line: # if the keyword exists on the current line...
print(file_path) # print the file path
break # no need to iterate over the rest of the file
except (IOError, OSError): # ignore read and permission errors
pass
我们还想了解该计划中的问题是什么?这不正是你所期望的吗?对于excel处理,pandas是一个很好的选择。Python无法读取.xlsx格式的excel电子表格,除了CSV格式的(文本文件)和非专有的电子表格。要以原生Excel.xlsx格式阅读它们,您需要下载并安装一些第三方扩展模块并使用它。有几种免费的。使用诸如
os.walk
、os.path.join
、open
等功能编写的代码可以通过以下方式简化:。它还消除了Path
处理的那些函数中可能出现的一些错误。这是一个很棒的模块这是一个显示转换的表格[