【发布时间】:2021-12-17 00:05:29
【问题描述】:
我有以下问题:我有 7 个列表表示星期几,我想为每个列表从 .txt 文件加载值。
文件内容:
[50, 54, 29, 33, 22, 100, 45, 54, 89, 75]
[80, 98, 40, 43, 43, 80, 50, 60, 79, 30]
[10, 7, 80, 43, 48, 82, 33, 55, 83, 80]
[15、20、38、10、36、50、20、26、45、20]
[20、25、47、18、56、70、30、36、65、28]
[122、140、245、128、156、163、90、140、150、128]
[100, 130, 234, 114, 138, 156, 107, 132, 134, 148]
我在下面包含了代码 sn-ps:
mon_sales = []
tue_sales = []
wed_sales = []
thu_sales = []
fri_sales = []
sat_sales = []
sun_sales = []
week_sales = [mon_sales, tue_sales, wed_sales, thu_sales,
fri_sales, sat_sales, sun_sales]
def load_sales(file_path):
"""
Loads the data in the sales list from a file.
file_path specifies the path of the file to load
Reports file exception if loading fails
"""
print('Loading sales data from a file: ', file_path)
print(week_sales)
for day_sales in week_sales:
day_sales.clear()
print(week_sales)
for day_sales in week_sales:
try:
with open('sales.txt', 'r') as input_file:
for line in input_file:
stripped_line = line.strip()
line_list = stripped_line.split('\n')
day_sales.append(line_list[0])
except:
print('omething went wrong while saving the data.')
print(week_sales)
问题在于,程序将文件的内容复制为一周中每一天的附加列表,而不是 .txt 文件中的一行。
我对如何改变这一点没有任何想法,我只是在学习 python,需要你的帮助来解决这个问题。
如何编写一个程序,仅将文本文件的一行中的值添加到每个星期几的列表中?
【问题讨论】: