在Python中将变量从文件获取到int()时出错
我试图从一些文件中的变量中获取一个值,下面是代码:在Python中将变量从文件获取到int()时出错,python,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)
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”之类的内容呢?如果
find
找不到您要搜索的字符串,它将返回-1。因此,您可以检查search.find(word)
的返回值,查看是否实际找到了word
此时,即使未找到搜索的单词,您也只需继续
find\u start
将结束为6,find\u end
将结束为8,并且可能search[6:8]
包含字符“RE”,这将导致出现错误消息。如果find
找不到正在搜索的字符串,它将返回-1。因此,您可以检查search.find(word)
的返回值,查看是否实际找到了word
此时,即使未找到搜索的单词,您也只需继续
find\u start
将以6结尾,find\u end
以8结尾,并且可能search[6:8]
包含字符“RE”,这会导致出现错误消息。您可以这样解决它:
try:
int(somestring)
except (ValueError, TypeError):
pass # not an int... what do you want to do now?
或者,如果您总是检查只应为数字的字符串:
if somestring.isdigit():
你可以这样解决:
try:
int(somestring)
except (ValueError, TypeError):
pass # not an int... what do you want to do now?
或者,如果您总是检查只应为数字的字符串:
if somestring.isdigit():
是否有输出错误的文件的示例?是否有输出错误的文件的示例?请切换顺序。清洁剂应该是第一个。@S.Lott:很公平,我已经改变了:)请改变顺序。更清洁的解决方案应该是第一个。@S.Lott:很公平,我已经改变了:)谢谢,你说得对,我还是继续,明白了吗?谢谢,你说得对,我还是继续,明白了吗