用python將文本中的數(shù)據(jù)讀取?
代碼如下:
#coding=utf-8
# 從文件中加載數(shù)據(jù)
def load_numbers(file):
numbers = []
with open(file, 'r') as f:
for line in f.readlines():
numbers.append(int(line))
return numbers
if __name__ == '__main__':
# 從文件 data.txt 中加載數(shù)字
numbers = load_numbers('data.txt')
# 區(qū)間下限
min = 10
# 區(qū)間上限
max = 30
# 統(tǒng)計(jì)區(qū)間數(shù)字個(gè)數(shù)
cnt = 0
for val in numbers:
# 如果不要包含上下限,去掉 = 號(hào)
if val >= min and val
cnt = cnt + 1
# 將結(jié)果保存到文件 result.txt 中
with open('result.txt', 'w') as f:
f.write('[%d,%d], %d' % (min, max, cnt))
print('done.')