How to write data to a file based on the year in Python?
You can use file operations in Python to write data to a file by year. Here is an example code:
data = [
{"year": 2020, "value": 100},
{"year": 2021, "value": 200},
{"year": 2020, "value": 150},
{"year": 2022, "value": 300}
]
# 按年份将数据分组
data_by_year = {}
for item in data:
year = item['year']
value = item['value']
if year in data_by_year:
data_by_year[year].append(value)
else:
data_by_year[year] = [value]
# 按年份写入文件
for year, values in data_by_year.items():
filename = f"data_{year}.txt"
with open(filename, 'w') as file:
for value in values:
file.write(str(value) + '\n')
After running the above code, three files will be generated: data_2020.txt, data_2021.txt, and data_2022.txt. The data in each file is written according to the corresponding year, for example, the data in data_2020.txt file is:
100
150
You can modify the code according to your specific needs, such as the data format and file name.