【python基础教程】使用python读写各种格式的文件

引言

今天,小哥给大家提供了丰富的文件读写功能,可应用于各种文件格式。本篇博客将总结Python中读写各类文件的方法,包括文本文件、CSV文件、JSON文件、Excel文件等。无论你是初学者还是有经验的开发者,这里都将为你提供一份全面的文件操作指南。

1. 文本文件

读取文本文件

file_path = 'example.txt'
with open(file_path, 'r') as file:
    content = file.read()
    print(content)

逐行读取文本文件

file_path = 'example.txt'
with open(file_path, 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())

写入文本文件

file_path = 'output.txt'
with open(file_path, 'w') as file:
    file.write('Hello, Python!\n')
    file.write('This is a guide to file operations in Python.')

2. CSV文件

读取CSV文件

import csv

file_path = 'example.csv'
with open(file_path, 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

写入CSV文件

import csv

file_path = 'output.csv'
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]

with open(file_path, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

写入csv带标题行

import csv

# 数据
data = [
    {'Name': '小米', 'Age': 25, 'City': '北京'},
    {'Name': '苹果', 'Age': 30, 'City': '加州'},
    {'Name': '华为', 'Age': 28, 'City': '深圳'}
]

# CSV文件路径
file_path = 'output.csv'

# 写入CSV文件
with open(file_path, 'w', newline='') as file:
    # 提取标题行
    fieldnames = data[0].keys()

    # 创建CSV写入对象
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    # 写入标题行
    writer.writeheader()

    # 写入数据
    writer.writerows(data)

print(f'CSV文件已成功写入:{file_path}')

3. JSON文件

读取JSON文件

import json

file_path = 'example.json'
with open(file_path, 'r') as file:
    data = json.load(file)
    print(data)

写入JSON文件

import json

file_path = 'output.json'
data = {'name': 'John', 'age': 28}

with open(file_path, 'w') as file:
    json.dump(data, file)

4. Excel文件

使用pandas库读取Excel文件

import pandas as pd

file_path = 'example.xlsx'
df = pd.read_excel(file_path)
print(df)

使用pandas库写入Excel文件

import pandas as pd

file_path = 'output.xlsx'
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)

df.to_excel(file_path, index=False)
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值