searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

平时经常会使用到的Python 脚本(2)

2024-11-22 17:34:56
0
0

1. CSV 文件读写

读取和写入 CSV 文件,常用于数据表格处理。

import csv

# 读取 CSV 文件
with open('data.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

# 写入 CSV 文件
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 25])
    writer.writerow(['Bob', 30])

广泛用于处理结构化数据,例如电子表格和数据库导出。

2. JSON 文件读写

读取和写入 JSON 格式的数据,适合存储复杂数据结构。

import json

# 写入 JSON 文件
data = {'name': 'Alice', 'age': 25}
with open('data.json', 'w', encoding='utf-8') as jsonfile:
    json.dump(data, jsonfile)

# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as jsonfile:
    data = json.load(jsonfile)
    print(data)

常用于 API 数据交互和配置文件管理。

 

0条评论
0 / 1000
王****际
180文章数
2粉丝数
王****际
180 文章 | 2 粉丝
原创

平时经常会使用到的Python 脚本(2)

2024-11-22 17:34:56
0
0

1. CSV 文件读写

读取和写入 CSV 文件,常用于数据表格处理。

import csv

# 读取 CSV 文件
with open('data.csv', newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        print(row)

# 写入 CSV 文件
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Name', 'Age'])
    writer.writerow(['Alice', 25])
    writer.writerow(['Bob', 30])

广泛用于处理结构化数据,例如电子表格和数据库导出。

2. JSON 文件读写

读取和写入 JSON 格式的数据,适合存储复杂数据结构。

import json

# 写入 JSON 文件
data = {'name': 'Alice', 'age': 25}
with open('data.json', 'w', encoding='utf-8') as jsonfile:
    json.dump(data, jsonfile)

# 读取 JSON 文件
with open('data.json', 'r', encoding='utf-8') as jsonfile:
    data = json.load(jsonfile)
    print(data)

常用于 API 数据交互和配置文件管理。

 

文章来自个人专栏
文章 | 订阅
0条评论
0 / 1000
请输入你的评论
0
0