python之文件操作

Python 提供了丰富的文件处理功能,包括文件的读取、写入和追加等操作。

原文地址可以访问我的博客:python之文件操作

1. 打开文件:
要打开文件,可以使用 open 函数。语法如下:

# 打开文件以进行读取(默认模式)
file = open("example.txt", "r")

# 打开文件以进行写入
file = open("example.txt", "w")

# 打开文件以进行追加
file = open("example.txt", "a")

2. 读取文件内容:

# 读取整个文件内容
content = file.read()
print(content)

3. 逐行读取文件:

# 逐行读取文件
file = open("example.txt", "r")

for line in file:
    print(line.strip())  # 去除行尾的换行符

4. 写入文件:

# 写入内容到文件
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("How are you?")
file.close()

5. 追加内容到文件:

# 追加内容到文件
file = open("example.txt", "a")
file.write("\nAppending new content.")
file.close()

6. 使用 with 语句自动关闭文件:

# 使用 with 语句自动关闭文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)
# 文件自动关闭,无需显式调用 close 方法

7. 检查文件是否存在:

import os

if os.path.exists("example.txt"):
    print("文件存在")
else:
    print("文件不存在")

8. 复制文件:

import shutil

shutil.copy("source.txt", "destination.txt")

9. 删除文件:

import os

os.remove("example.txt")

这是一个简单的关于 Python 文件操作的教程,希望对你有帮助.转载请表明出处icon-default.png?t=N7T8http://blog.tsaqhm.cn/

  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值