温馨提示×

CentOS Python文件操作指南

小樊
37
2025-11-08 05:10:24
栏目: 编程语言

CentOS Python文件操作指南

1. 环境准备:安装Python

在CentOS系统上使用Python进行文件操作前,需确保已安装Python 3(推荐)。通过以下命令检查Python版本:

python3 --version

若未安装,使用yum包管理器安装:

sudo yum install python3 -y

安装完成后,验证安装结果:

python3 --version  # 应输出Python 3.x版本号

2. 文件操作基础流程

Python通过open()函数实现文件操作,核心流程包括打开文件→操作文件→关闭文件。其中,使用with语句是推荐方式,可自动管理文件关闭,避免资源泄露。

2.1 打开文件:open()函数

open()函数的基本语法为:

file = open(file_path, mode, encoding='utf-8')
  • file_path:文件路径(如'data.txt'表示当前目录下的data.txt文件);
  • mode:打开模式(决定操作权限,常见模式见下文);
  • encoding:字符编码(推荐使用utf-8,避免中文乱码)。

常见模式说明

模式 描述 示例
'r' 只读模式(默认) open('data.txt', 'r')
'w' 写入模式(覆盖原有内容,文件不存在则创建) open('output.txt', 'w')
'a' 追加模式(在文件末尾添加内容,文件不存在则创建) open('log.txt', 'a')
'rb' 二进制读取模式(如图片、音频) open('image.png', 'rb')
'wb' 二进制写入模式 open('output.png', 'wb')

2.2 读取文件内容

读取文件时,可根据文件大小选择合适的方法:

  • 读取全部内容read()方法,返回字符串(文本模式)或字节串(二进制模式);
  • 逐行读取readline()(读取一行)或readlines()(返回所有行的列表);
  • 遍历文件对象:直接遍历文件对象,逐行处理(内存效率高,适合大文件)。

示例代码

# 使用with语句读取文件(推荐)
with open('data.txt', 'r', encoding='utf-8') as file:
    # 读取全部内容
    content = file.read()
    print("全部内容:\n", content)
    
    # 逐行读取(返回列表)
    file.seek(0)  # 将文件指针移回开头
    lines = file.readlines()
    print("所有行:", lines)
    
    # 遍历文件对象(逐行处理)
    file.seek(0)
    for line in file:
        print("每行内容:", line.strip())  # strip()去除行末换行符

2.3 写入/追加文件内容

写入文件时,需指定模式为'w'(覆盖)或'a'(追加),使用write()(写入字符串)或writelines()(写入字符串列表)方法。

示例代码

# 写入文件(覆盖原有内容)
with open('output.txt', 'w', encoding='utf-8') as file:
    file.write("Hello, CentOS!\n")  # 写入单行
    file.write("This is a Python file operation example.\n")

# 追加内容到文件末尾
with open('output.txt', 'a', encoding='utf-8') as file:
    file.write("Appended content at " + "2025-11-08.\n")

# 写入多行(列表形式)
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('multiline.txt', 'w', encoding='utf-8') as file:
    file.writelines(lines)

3. 异常处理:避免程序崩溃

文件操作可能遇到文件不存在FileNotFoundError)、权限不足PermissionError)等异常,需用try-except语句捕获处理。

示例代码

try:
    with open('nonexistent.txt', 'r', encoding='utf-8') as file:
        content = file.read()
except FileNotFoundError:
    print("错误:文件不存在,请检查路径!")
except PermissionError:
    print("错误:没有权限访问该文件!")
except Exception as e:
    print(f"发生未知错误:{e}")

4. 文件操作进阶技巧

4.1 检查文件是否存在

使用os.path.exists()函数判断文件是否存在,避免不必要的异常。

import os
if os.path.exists('data.txt'):
    print("文件存在,可以进行操作。")
else:
    print("文件不存在,需创建或检查路径。")

4.2 删除文件

使用os.remove()函数删除文件,需先检查文件是否存在。

import os
if os.path.exists('temp.txt'):
    os.remove('temp.txt')
    print("文件已删除。")
else:
    print("文件不存在,无法删除。")

4.3 处理二进制文件

对于图片、音频等二进制文件,需使用'rb'(读取)或'wb'(写入)模式。

# 读取二进制文件(如图片)
with open('image.jpg', 'rb') as file:
    binary_data = file.read()
    print("二进制数据长度:", len(binary_data))

# 写入二进制文件
with open('copy_image.jpg', 'wb') as file:
    file.write(binary_data)

4.4 读写CSV文件

使用csv模块处理CSV文件(逗号分隔值),支持读取和写入表格数据。

import csv

# 写入CSV文件
with open('data.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])  # 写入表头
    writer.writerow(['Alice', 30, 'New York'])
    writer.writerow(['Bob', 25, 'London'])

# 读取CSV文件
with open('data.csv', 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print("CSV行数据:", row)

5. 注意事项

  • 文件路径:可使用相对路径(如'data.txt',相对于当前脚本目录)或绝对路径(如'/home/user/data.txt');
  • 编码问题:始终指定encoding='utf-8',避免中文或其他特殊字符乱码;
  • 资源释放:即使使用with语句,也应避免在文件操作过程中频繁打开/关闭文件,影响性能;
  • 权限问题:确保对目标文件或目录有足够的读写权限(可通过chmod命令修改权限)。

0