python文件操作

在 Python 中,文件处理是一个常见的任务,主要包括文件的打开、读取、写入和关闭。以下是 Python 文件处理的基本操作方法:

  1. 打开文件:使用 open() 函数。
  2. 读取文件:使用 read(), readline(), readlines() 方法。
  3. 写入文件:使用 write(), writelines() 方法。
  4. 关闭文件:使用 close() 方法,或者使用 with 语句自动管理文件的关闭。

文件处理的基本操作

1. 打开文件
file = open('example.txt', 'r')  # 以只读模式打开文件
2. 读取文件
  • 读取整个文件内容

    content = file.read()
    
  • 读取一行

    line = file.readline()
    
  • 读取所有行

    lines = file.readlines()
    
3. 写入文件
  • 写入字符串

    file = open('example.txt', 'w')  # 以写模式打开文件
    file.write('Hello, World!')
    
  • 写入多行

    lines = ['First line\n', 'Second line\n', 'Third line\n']
    file.writelines(lines)
    
4. 关闭文件
file.close()
使用 with 语句

with 语句可以自动管理文件的打开和关闭,推荐使用这种方式。

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

完整的代码示例

import os

# 写入文件示例
def write_to_file(file_path, content):
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(content)
    print(f"Content written to {file_path}")

# 读取文件示例
def read_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    print(f"Content read from {file_path}:\n{content}")
    return content

# 追加写入文件示例
def append_to_file(file_path, content):
    with open(file_path, 'a', encoding='utf-8') as file:
        file.write(content)
    print(f"Content appended to {file_path}")

# 示例文件路径
file_path = 'example.txt'

# 写入内容
write_to_file(file_path, "Hello, World!\nThis is a test file.")

# 读取内容
read_from_file(file_path)

# 追加内容
append_to_file(file_path, "\nAppending a new line.")

# 再次读取内容
read_from_file(file_path)

# 删除示例文件
os.remove(file_path)
print(f"{file_path} has been deleted.")

总结

  • 使用 open() 函数可以打开文件,指定模式如 'r'(只读)、'w'(写入)、'a'(追加)等。
  • 使用 read(), readline(), readlines() 方法可以读取文件内容。
  • 使用 write(), writelines() 方法可以写入文件内容。
  • 使用 close() 方法关闭文件,或者使用 with 语句自动管理文件的关闭。
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鱼爱吃火锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值