【问题标题】:Loading a file into a list in Python在 Python 中将文件加载到列表中
【发布时间】: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,需要你的帮助来解决这个问题。

如何编写一个程序,仅将文本文件的一行中的值添加到每个星期几的列表中?

【问题讨论】:

    标签: python file load


    【解决方案1】:

    使用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]
    

    【讨论】:

    • 谢谢你,你帮了我很多!
    猜你喜欢
    • 2017-10-05
    • 2016-06-04
    • 2012-03-20
    • 2014-02-12
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多