這個問題已經使用了很長時間了,但似乎找不到解決方案。我使用excelfiles函數來創建所有excelfiles的列表,包括在指定目錄中名稱中的「tst」。之後,我想用locate_vals-function從每個文檔中讀取特定的單元格,但似乎無法從文件列表中讀取文件。也許有一個非常簡單的解決方案,我只是看不到?我得到的錯誤信息在底部。從文件列表中讀取文件
這是一個更重要的任務,我問了昨天的幫助(「Search through directories for specific Excel files and compare data from these files with inputvalues」)的一部分,但我似乎無法找到任何回答這個問題,我想這可能是最好給它它是自己的一個線程。糾正我,如果我錯了,我會刪除它:)
import xlrd
import os, fnmatch
#globals
start_dir = 'C:/eclipse/TST-folder'
def excelfiles(pattern):
file_list = []
for root, dirs, files in os.walk(start_dir):
for filename in files:
if fnmatch.fnmatch(filename.lower(), pattern):
if filename.endswith(".xls") or filename.endswith(".xlsx") or filename.endswith(".xlsm"):
file_list.append(os.path.join(root, filename))
return file_list
file_list = excelfiles('*tst*') # only accept docs hwom title includes tst
for i in file_list: print i
'''Location of each val from the excel spreadsheet'''
def locate_vals():
val_list = []
for file in file_list:
wb = xlrd.open_workbook(os.path.join(start_dir, file))
sheet = wb.sheet_by_index(0)
for vals in file:
weightvalue = file_list.sheet.cell(3, 3).value
lenghtvalue = sheet.cell(3, 2).value
speedval = sheet.cell(3, 4).value
ERRORMESSAGE:
Traceback (most recent call last):
File "C:\Users\Håvard\Documents\Skulearbeid\UMB\4. Semester Vår\Inf120 Programmering og databehandling\Workspace\STT\tst_mainsheet.py", line 52, in <module>
print locate_vals()
File "C:\Users\Håvard\Documents\Skulearbeid\UMB\4. Semester Vår\Inf120 Programmering og databehandling\Workspace\STT\tst_mainsheet.py", line 48, in locate_vals
weightvalue = file_list.sheet.cell(3, 3).value
AttributeError: 'list' object has no attribute 'sheet'
謝謝!我會用這種方法來代替。最近一段時間,我一直在爲一個項目忙碌起來,所以我的劇本目前有點亂。 – Havard
難道你不認爲這是更完整的答案嗎? :)(謝謝!) –
是的,我做:)再次感謝! – Havard