【问题标题】:Convert only last X rows of csv into json仅将最后 X 行 csv 转换为 json
【发布时间】:2021-10-21 08:52:08
【问题描述】:

我有以下 python 代码将 csv 文件转换为 json 文件。

def make_json_from_csv(csv_file_path, json_file_path, unique_column_name):
    import csv
    import json
    # create a dictionary
    data = {}

    # Open a csv reader called DictReader
    with open(csv_file_path, encoding='utf-8') as csvf:
        csv_reader = csv.DictReader(csvf)

        primary_key_column_name = unique_column_name.lstrip()  # remove leading space in string
        # Convert each row into a dictionary
        # and add it to data
        for rows in csv_reader:
            key = rows[primary_key_column_name]
            data[key] = rows

    # Open a json writer, and use the json.dumps()
    # function to dump data
    with open(json_file_path, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))
    return None

上面的代码会将 CSV 文件中的所有行转换为 json 文件。我只想将最后 X 行转换为 json。

我正在使用 python v3。

【问题讨论】:

  • 您使用的是哪个特定版本的 Python 3?
  • @Dani Mesejo,我正在使用 python v3.8.5

标签: python python-3.x csv


【解决方案1】:

在 Python 3.6+ 中,dict 保持插入顺序,因此要获取字典的最后一行,只需:

from itertools import islice

x = 5
d = {}
for i, v in enumerate("abcdedfghi"):
    d[i] = v

d = dict(islice(d.items(), len(d) - x, len(d)))
print(d)

输出

{5: 'd', 6: 'f', 7: 'g', 8: 'h', 9: 'i'}

基本上将这些行添加(更改)到您的代码中:

from itertools import islice

x = 5
data = dict(islice(data.items(), len(data) - x, len(data)))

# Open a json writer, and use the json.dumps()
# function to dump data
with open(json_file_path, 'w', encoding='utf-8') as jsonf:
    jsonf.write(json.dumps(data, indent=4))

【讨论】:

    【解决方案2】:

    我想在 Dani Mesejo 的回答的基础上回答我自己的问题。功劳完全归功于他。

    def make_json(csv_file_path, json_file_path,
                  unique_column_name, no_of_rows_to_extract):
        import csv
        import json
        from itertools import islice
        # create a dictionary
        data = {}
    
        # Open a csv reader called DictReader
        with open(csv_file_path, encoding='utf-8') as csvf:
            csv_reader = csv.DictReader(csvf)
    
            primary_key_column_name = unique_column_name.lstrip()  # remove leading space in string
            # Convert each row into a dictionary
            # and add it to data
            for rows in csv_reader:
                key = rows[primary_key_column_name]
                data[key] = rows
    
        data = dict(islice(data.items(), len(data) - no_of_rows_to_extract, len(data)))
    
        # Open a json writer, and use the json.dumps()
        # function to dump data
        with open(json_file_path, 'w', encoding='utf-8') as jsonf:
            jsonf.write(json.dumps(data, indent=4))
        return None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-21
      • 2015-08-23
      • 2019-08-21
      • 2011-04-27
      • 1970-01-01
      相关资源
      最近更新 更多