python-3.x - 处理“str”对象在函数中没有“read”属性
问题描述
遇到处理“AttributeError”的编程问题。我得到了一个打开的文件,需要首先创建一个所有单词的列表(假设它们的数字),然后找到一年,然后是 12 个数字,但是在我的一个函数中一直出现这个错误。我认为我在读取文件或在函数之间传输信息时做错了。
这是我的主要功能:
# process_rainfall_data_w_functions.py
# Instructor-supplied driver for the rainfall_data_functions module.
import sys
import rainfall_data_functions
def main():
"""
The main driver function for the functions in the module
rainfall_data_functions.py.
"""
if len(sys.argv) == 1:
rainfall_data_functions.display_opening_screen()
rainfall_data_functions.display_program_info()
sys.exit()
f = open(sys.argv[1])
rainfall_data_functions.process_rainfall_file(f)
f.close()
print("\nOK ... Program now terminating.")
input("Press Enter to continue ... ")
main()
和我的职能:
def process_rainfall_file(f):
numbers = list(f.read().split())
year = input('Enter year for which you want rainfall data: ')
rain_nums, rain_dict = process_data(year, numbers)
read_information(rain_nums, rain_dict, year)
def year_input():
# asks user for year
year = input('Enter year for which you want rainfall data: ')
return year
def process_data(year, numbers):
# finds index of matching year in text list
year_index = numbers.index(year)
# creates two lists for processing values
rain_string = []
rain_nums = []
# collects the twelve values after year in list number
for i in range(year_index, year_index + 12):
rain_string.append(numbers[i+1])
# changes the twelve strings into float values
for i in rain_string:
rain_nums.append(float(i))
# create list with twelve months
months_of_year = ['January', 'February', 'March', 'April', 'May',
'June', 'July', 'Augest', 'September', 'October',
'November', 'December']
# creates dict with months and rain values matched up
rain_dict = dict(zip(months_of_year, rain_nums))
# returns the list and dict
return rain_nums, rain_dict
def read_information(rain_nums, rain_dict, year):
# prints first text box with rain values
print('\n===== Rainfall summary for {}'.format(year), end='')
print("""
January..... {[0]:4.1f} July........ {[6]:4.1f}
February.... {[1]:4.1f} August...... {[7]:4.1f}
March....... {[2]:4.1f} September... {[8]:4.1f}
April....... {[3]:4.1f} October..... {[9]:4.1f}
May......... {[4]:4.1f} November.... {[10]:4.1f}
June........ {[5]:4.1f} December.... {[11]:4.1f}"""
.format(rain_nums, rain_nums, rain_nums, rain_nums, rain_nums,
rain_nums, rain_nums, rain_nums, rain_nums, rain_nums,
rain_nums, rain_nums), end='')
# find total of all float rain values under total_rain
total_rain = 0
for i in range(12):
total_rain += float(rain_nums[i])
# finds average rain
avg_rain = total_rain/len(rain_nums)
# finds max rain value and matches it with its month in dict
max_month = max(rain_dict, key=rain_dict.get)
# finds min rain value and matches it with its month in dict
min_month = min(rain_dict, key=rain_dict.get)
# prints second text box after calculations
print("""
===== Total rainfall for the year... {:<7}
===== Average monthly rainfall...... {:<7}
===== Month with highest rainfall... {:<7}
===== Month with lowest rainfall.... {:<7}"""
.format(round(total_rain, 1),
round(avg_rain, 1), max_month, min_month))
# pause
input('Press Enter to continue ...')
据说错误发生在这个函数中:
J:\*******\*******\rainfall_data_functions.py in process_rainfall_file(f)
46 def process_rainfall_file(f):
47 numbers = list(f.split())
---> 48 year = input('Enter year for which you want rainfall data: ')
49 rain_nums, rain_dict = process_data(year, numbers)
50 read_information(rain_nums, rain_dict, year)
AttributeError: 'str' object has no attribute 'read'
ps 在通过函数发送之前给我打开的文件,并且必须是。
解决方案
推荐阅读
- google-apps-script - 如何在 Google Doc Add-on 的 GAS 项目中按名称获取 namedRanges
- node.js - 使用证书中的公钥将引发错误
- machine-learning - h2o: Flow UI, ROC with drf without fold
- java - 如何修复“创建文档实例时出错。原因:org.xml.sax.SAXParseException;必须为元素类型“mapper”声明属性“class”。
- python - 从 url 获取数据并将其放入 DataFrame
- ruby-on-rails - 是否可以在不使用密钥 ID 和密钥(Ruby on Rails)的情况下在 S3 存储桶上创建文件?
- c++ - 如何从用户那里获取方程的输入并在c ++中对其进行评估
- fullcalendar - 控制 FullCalendar 4 时间网格槽高度
- konvajs - vue-konva 将自定义样式传递给 div.konvajs-content & canvas
- node.js - 如何在突变 graphQL Playground 中传递变量?