我想從一些文件裏面變量值獲取變量從文件到INT(),這裏是代碼:錯誤在Python
path = '/opt/log/...'
word = 'somevariable'
def enumeratepaths(path=path):
paths = []
for dirpath, dirnames, files in os.walk(path):
for file in files:
fullpath = os.path.join(dirpath, file)
paths.append(fullpath)
return paths
def read_files(file):
try:
file_open = open(file, 'r')
search = file_open.read()
find = search.find(word)
find_start = find + 7
find_stop = find + 9
result = int(search[find_start:find_stop])
return int(result)
finally:
file_open.close()
def main():
for files in enumeratepaths():
read_files(files)
if __name__ == "__main__":
main()
的問題是,一些文件不內部有變量,因爲發生了一些錯誤。在這種情況下,該腳本將返回一個錯誤:
result = int(search[find_start:find_stop])
ValueError: invalid literal for int(): RE
我想這些值作爲int
,但我堅持。
還有一個問題:如果文件沒有那個搜索值,它怎麼會返回像「RE」這樣的東西?
你有該文件的樣本被輸出錯誤? – Duniyadnd 2011-03-21 18:39:14