我有以下問題:我有 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]
我在下面包含了代碼片段:
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,需要你的幫助來解決這個問題。
如何撰寫程式以將文本檔案的僅一行中的值添加到每個包含一周中的天數的串列中?
uj5u.com熱心網友回復:
使用json庫:
sales.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]
代碼
import json
with open('sales.txt') as input_file:
result = [json.loads(s) for s in input_file]
[[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]]
如果您的檔案在每行資料之間確實有空行,請使用:
import json
with open('filename.csv') as input_file:
def try_load(s):
try:
return json.loads(s)
except json.decoder.JSONDecodeError:
return None
result = [s for s in map(try_load, input_file) if s]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348466.html
下一篇:美麗的湯,只找一種圖案
