Python文件操作全攻略

从零开始的Python学习:文件操作指南

Python作为一门强大的编程语言,文件操作是其核心功能之一。掌握文件操作能帮助开发者高效处理数据存储、读取和修改任务。

文件的基本操作

在Python中,使用内置的open()函数来操作文件。该函数接受文件路径和模式作为参数,返回一个文件对象。

file = open('example.txt', 'r')
content = file.read()
file.close()

文件模式包括:

  • 'r':读取(默认)
  • 'w':写入(会覆盖现有内容)
  • 'a':追加
  • 'x':独占创建
  • 'b':二进制模式
  • 't':文本模式(默认)

安全文件处理

为避免文件未正确关闭导致资源泄露,推荐使用with语句。这种方式会在代码块执行完毕后自动关闭文件。

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

文件读取方法

Python提供了多种读取文件内容的方式:

  • read():读取整个文件
  • readline():读取单行
  • readlines():读取所有行并返回列表
with open('example.txt', 'r') as file:
    for line in file:  # 逐行读取
        print(line.strip())

文件写入操作

写入文件时,需使用写入模式('w')或追加模式('a')。注意写入模式会覆盖原有内容。

with open('output.txt', 'w') as file:
    file.write('Hello, World!\n')
    file.writelines(['Line 1\n', 'Line 2\n'])

文件位置操作

使用seek()tell()方法可以控制和获取文件指针位置:

with open('example.txt', 'rb') as file:
    file.seek(5)  # 移动到第5个字节
    print(file.tell())  # 输出当前位置

二进制文件处理

对于非文本文件,如图片或视频,需要使用二进制模式('b'):

with open('image.jpg', 'rb') as file:
    data = file.read()

文件与目录管理

osos.path模块提供了丰富的文件和目录操作功能:

import os

if os.path.exists('example.txt'):
    print("文件存在")
    print(f"文件大小:{os.path.getsize('example.txt')}字节")

高级文件操作

pathlib模块提供了面向对象的文件路径操作方式:

from pathlib import Path

path = Path('example.txt')
if path.exists():
    print(f"文件内容:{path.read_text()}")

CSV文件处理

Python内置csv模块简化CSV文件操作:

import csv

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

JSON文件处理

json模块使JSON文件的读写变得简单:

import json

data = {'name': 'John', 'age': 30}
with open('data.json', 'w') as file:
    json.dump(data, file)

with open('data.json', 'r') as file:
    loaded_data = json.load(file)

异常处理

文件操作时应当处理可能出现的异常:

try:
    with open('nonexistent.txt', 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("文件不存在")
except IOError:
    print("读写错误")

通过掌握这些文件操作技术,Python开发者能够高效处理各种数据持久化需求。实际应用中应根据具体场景选择合适的方法,并始终注意资源管理和错误处理。

5G.okacbd111.asia/PoSt/1123_525732.HtM
5G.okacbd112.asia/PoSt/1123_033492.HtM
5G.okacbd113.asia/PoSt/1123_399812.HtM
5G.okacbd114.asia/PoSt/1123_206824.HtM
5G.okacbd115.asia/PoSt/1123_710392.HtM
5G.okacbd116.asia/PoSt/1123_349878.HtM
5G.okacbd117.asia/PoSt/1123_720239.HtM
5G.okacbd118.asia/PoSt/1123_438516.HtM
5G.okacbd119.asia/PoSt/1123_794952.HtM
5G.okacbd120.asia/PoSt/1123_082067.HtM
5G.okacbd111.asia/PoSt/1123_471214.HtM
5G.okacbd112.asia/PoSt/1123_106531.HtM
5G.okacbd113.asia/PoSt/1123_905595.HtM
5G.okacbd114.asia/PoSt/1123_294985.HtM
5G.okacbd115.asia/PoSt/1123_925893.HtM
5G.okacbd116.asia/PoSt/1123_986568.HtM
5G.okacbd117.asia/PoSt/1123_493134.HtM
5G.okacbd118.asia/PoSt/1123_129252.HtM
5G.okacbd119.asia/PoSt/1123_144437.HtM
5G.okacbd120.asia/PoSt/1123_767650.HtM
5G.okacbd111.asia/PoSt/1123_758369.HtM
5G.okacbd112.asia/PoSt/1123_478775.HtM
5G.okacbd113.asia/PoSt/1123_644028.HtM
5G.okacbd114.asia/PoSt/1123_457915.HtM
5G.okacbd115.asia/PoSt/1123_989412.HtM
5G.okacbd116.asia/PoSt/1123_473264.HtM
5G.okacbd117.asia/PoSt/1123_271539.HtM
5G.okacbd118.asia/PoSt/1123_944299.HtM
5G.okacbd119.asia/PoSt/1123_318633.HtM
5G.okacbd120.asia/PoSt/1123_307178.HtM
5G.okacbd111.asia/PoSt/1123_278021.HtM
5G.okacbd112.asia/PoSt/1123_998088.HtM
5G.okacbd113.asia/PoSt/1123_151233.HtM
5G.okacbd114.asia/PoSt/1123_976443.HtM
5G.okacbd115.asia/PoSt/1123_310792.HtM
5G.okacbd116.asia/PoSt/1123_010011.HtM
5G.okacbd117.asia/PoSt/1123_421866.HtM
5G.okacbd118.asia/PoSt/1123_883117.HtM
5G.okacbd119.asia/PoSt/1123_157438.HtM
5G.okacbd120.asia/PoSt/1123_382768.HtM
5G.okacbd111.asia/PoSt/1123_766972.HtM
5G.okacbd112.asia/PoSt/1123_149271.HtM
5G.okacbd113.asia/PoSt/1123_325705.HtM
5G.okacbd114.asia/PoSt/1123_787316.HtM
5G.okacbd115.asia/PoSt/1123_188319.HtM
5G.okacbd116.asia/PoSt/1123_919647.HtM
5G.okacbd117.asia/PoSt/1123_206628.HtM
5G.okacbd118.asia/PoSt/1123_264583.HtM
5G.okacbd119.asia/PoSt/1123_666170.HtM
5G.okacbd120.asia/PoSt/1123_914048.HtM
5G.okacbd111.asia/PoSt/1123_429669.HtM
5G.okacbd112.asia/PoSt/1123_651064.HtM
5G.okacbd113.asia/PoSt/1123_357170.HtM
5G.okacbd114.asia/PoSt/1123_861690.HtM
5G.okacbd115.asia/PoSt/1123_170847.HtM
5G.okacbd116.asia/PoSt/1123_731462.HtM
5G.okacbd117.asia/PoSt/1123_565910.HtM
5G.okacbd118.asia/PoSt/1123_984036.HtM
5G.okacbd119.asia/PoSt/1123_429913.HtM
5G.okacbd120.asia/PoSt/1123_753333.HtM
5G.okacbd111.asia/PoSt/1123_185006.HtM
5G.okacbd112.asia/PoSt/1123_881883.HtM
5G.okacbd113.asia/PoSt/1123_056707.HtM
5G.okacbd114.asia/PoSt/1123_813388.HtM
5G.okacbd115.asia/PoSt/1123_180209.HtM
5G.okacbd116.asia/PoSt/1123_216856.HtM
5G.okacbd117.asia/PoSt/1123_530226.HtM
5G.okacbd118.asia/PoSt/1123_778745.HtM
5G.okacbd119.asia/PoSt/1123_378118.HtM
5G.okacbd120.asia/PoSt/1123_325725.HtM
5G.okacbd111.asia/PoSt/1123_144364.HtM
5G.okacbd112.asia/PoSt/1123_257475.HtM
5G.okacbd113.asia/PoSt/1123_713589.HtM
5G.okacbd114.asia/PoSt/1123_264268.HtM
5G.okacbd115.asia/PoSt/1123_479677.HtM
5G.okacbd116.asia/PoSt/1123_848887.HtM
5G.okacbd117.asia/PoSt/1123_878776.HtM
5G.okacbd118.asia/PoSt/1123_250225.HtM
5G.okacbd119.asia/PoSt/1123_286435.HtM
5G.okacbd120.asia/PoSt/1123_300298.HtM

#牛客AI配图神器#

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务