Python基础:python语言中的文件操作+面试题目

Python语言中的文件操作是与外部数据交互的重要方式,主要通过内置的 open() 函数实现:

一、文件的打开与关闭

1. 打开文件

复制代码
# 基本语法:open(filename, mode, encoding=None)
# filename: 文件路径
# mode: 打开模式
# encoding: 编码方式(文本文件需要)

# 打开文本文件(默认模式为'r')
file = open("test.txt", "r", encoding="utf-8")

2. 关闭文件

复制代码
file.close()  # 一定要关闭文件释放资源

3. 打开模式

|----|--------------------------------|
| 模式 | 描述 |
| r | 只读模式(默认) |
| w | 写入模式(覆盖现有文件,文件不存在则创建) |
| a | 追加模式(在文件末尾添加内容) |
| x | 独占创建模式(文件存在则报错) |
| b | 二进制模式(与其他模式组合使用,如'rb', 'wb') |
| t | 文本模式(默认,与其他模式组合使用,如'rt', 'wt') |
| + | 读写模式(与其他模式组合使用,如'r+', 'w+') |

二、上下文管理器(with语句)

推荐使用 with 语句自动管理文件的打开和关闭:

复制代码
with open("test.txt", "r", encoding="utf-8") as file:
    # 文件操作代码
    content = file.read()
# 离开with块后,文件自动关闭

三、文件读取操作

1. 读取全部内容

复制代码
with open("test.txt", "r", encoding="utf-8") as file:
    content = file.read()  # 读取所有内容
    print(content)

2. 按行读取

复制代码
# 读取一行
with open("test.txt", "r", encoding="utf-8") as file:
    line = file.readline()  # 读取第一行
    print(line)

# 读取所有行(返回列表)
with open("test.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()  # 所有行组成的列表
    for line in lines:
        print(line.strip())  # 去除换行符

# 逐行读取(内存友好,适合大文件)
with open("test.txt", "r", encoding="utf-8") as file:
    for line in file:  # 文件对象是可迭代的
        print(line.strip())

四、文件写入操作

1. 写入字符串

复制代码
# 写入模式会覆盖现有内容
with open("test.txt", "w", encoding="utf-8") as file:
    file.write("Hello, World!\n")
    file.write("This is a test file.\n")

2. 写入多行

复制代码
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("test.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)  # 写入列表中的所有字符串

五、文件追加操作

复制代码
with open("test.txt", "a", encoding="utf-8") as file:
    file.write("This is appended content.\n")
    file.write("One more line.\n")

六、文件定位操作

1. 获取当前位置

复制代码
with open("test.txt", "r", encoding="utf-8") as file:
    file.read(5)  # 读取5个字符
    pos = file.tell()  # 获取当前位置
    print(pos)  # 5

2. 移动到指定位置

复制代码
with open("test.txt", "r", encoding="utf-8") as file:
    file.seek(0)  # 移动到文件开头
    content = file.read()
    
    file.seek(5)  # 移动到第6个字符位置
    content_part = file.read(10)  # 读取10个字符

七、二进制文件操作

用于处理图片、视频、音频等非文本文件:

复制代码
# 读取二进制文件
with open("image.jpg", "rb") as file:
    data = file.read()
    print(len(data))  # 文件大小(字节)

# 写入二进制文件
with open("copy_image.jpg", "wb") as file:
    file.write(data)  # 保存二进制数据

八、常用文件操作函数

1. 检查文件是否存在

复制代码
import os

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

2. 获取文件信息

复制代码
import os

# 文件大小
size = os.path.getsize("test.txt")
print(f"文件大小: {size} 字节")

# 最后修改时间
mtime = os.path.getmtime("test.txt")
import datetime
print(f"最后修改时间: {datetime.datetime.fromtimestamp(mtime)}")

# 是否为文件
is_file = os.path.isfile("test.txt")
print(f"是否为文件: {is_file}")

# 是否为目录
is_dir = os.path.isdir("test.txt")
print(f"是否为目录: {is_dir}")

3. 文件和目录操作

复制代码
import os
import shutil

# 创建目录
os.mkdir("new_dir")

# 递归创建目录
os.makedirs("parent_dir/child_dir", exist_ok=True)

# 重命名文件/目录
os.rename("test.txt", "new_test.txt")

# 删除文件
os.remove("new_test.txt")

# 删除目录
os.rmdir("new_dir")

# 递归删除目录
shutil.rmtree("parent_dir")

# 复制文件
shutil.copy("source.txt", "destination.txt")

# 复制目录
shutil.copytree("source_dir", "destination_dir")

# 移动文件/目录
shutil.move("source.txt", "new_location/")

4. 列出目录内容

复制代码
import os

# 列出目录中的文件和子目录
contents = os.listdir(".")
print(contents)

# 列出所有文件(递归)
for root, dirs, files in os.walk("."):
    print(f"当前目录: {root}")
    print(f"子目录: {dirs}")
    print(f"文件: {files}")

九、CSV文件操作

复制代码
import csv

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

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

# 使用字典读取和写入
with open("data.csv", "r", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["Name"], row["Age"])

with open("new_data.csv", "w", encoding="utf-8", newline="") as file:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({"Name": "Charlie", "Age": 35, "City": "Paris"})

十、JSON文件操作

复制代码
import json

# 读取JSON文件
with open("data.json", "r", encoding="utf-8") as file:
    data = json.load(file)
    print(data)

# 写入JSON文件
user = {
    "name": "Alice",
    "age": 25,
    "city": "New York",
    "hobbies": ["reading", "coding", "traveling"]
}

with open("user.json", "w", encoding="utf-8") as file:
    json.dump(user, file, ensure_ascii=False, indent=4)
    # ensure_ascii=False: 保留中文
    # indent=4: 美化输出,使用4个空格缩进

十一、异常处理

文件操作可能会出现各种错误,应使用异常处理:

复制代码
try:
    with open("nonexistent.txt", "r", encoding="utf-8") as file:
        content = file.read()
    print(content)
except FileNotFoundError:
    print("文件不存在")
except PermissionError:
    print("没有文件访问权限")
except UnicodeDecodeError:
    print("编码错误")
except Exception as e:
    print(f"发生错误: {e}")

十二、最佳实践

  1. 总是使用with语句 :自动管理文件关闭

  2. 指定编码 :文本文件操作时明确指定编码

  3. 处理异常 :捕获可能的文件操作错误

  4. 避免大文件一次性读取 :使用逐行读取处理大文件

  5. 使用合适的模式 :根据需求选择正确的打开模式

  6. 资源管理 :确保文件操作完成后释放资源

Python的文件操作功能强大且灵活,通过这些操作可以方便地与外部数据进行交互。

十三、面试习题

题目 1:选择题

以下哪个Python函数用于打开一个文件?

A. open()

B. read()

C. write()

D. close()
A. open()

题目 2:操作题

请编写一个Python程序,将用户输入的文本写入到一个文件中,然后读取该文件并输出其内容。

复制代码
# 题目2和题目4:文件写入与读取操作
def write_file_with_user_input(filename="user_input.txt"):
    """将用户输入的文本写入文件"""
    try:
        # 获取用户输入
        user_text = input("请输入要写入文件的文本:")
        
        # 使用with语句确保文件正确关闭
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(user_text)
        
        print(f"文本已成功写入文件:{filename}")
        
        # 读取并显示文件内容
        with open(filename, 'r', encoding='utf-8') as file:
            content = file.read()
        
        print(f"从文件读取的内容:{content}")
        return True
        
    except Exception as e:
        print(f"操作失败:{e}")
        return False

def write_file_with_fixed_content(filename="example.txt"):
    """将固定文本写入文件并读取(题目4)"""
    try:
        # 示例文本
        text = "Hello, Python!"
        
        # 写入文件
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(text)
        
        print(f"文本已写入文件:{filename}")
        
        # 读取文件
        with open(filename, 'r', encoding='utf-8') as file:
            content = file.read()
        
        print(f"读取的内容:{content}")
        return True
        
    except Exception as e:
        print(f"操作失败:{e}")
        return False

# 执行测试
if __name__ == "__main__":
    print("=== 测试题目2:用户输入写入文件 ===")
    # 为了方便测试,这里改为使用固定文本,实际使用时可以取消注释下面的行
    # write_file_with_user_input()
    
    # 使用固定文本进行演示
    with open("user_input.txt", 'w', encoding='utf-8') as f:
        f.write("这是一个测试文本")
    
    with open("user_input.txt", 'r', encoding='utf-8') as f:
        print(f"演示内容:{f.read()}")
    
    print("\n=== 测试题目4:固定文本写入文件 ===")
    write_file_with_fixed_content()

题目 3:填空题

在Python中,使用______函数可以打开一个文件,并指定文件的打开模式(例如:读取模式、写入模式等)。

当你完成文件操作后,应该使用______函数来关闭文件,释放系统资源。
open()、close()

题目 4:编程题

编写一个Python程序,将一段文本写入文件example.txt,然后读取文件内容并输出。要求:

以写模式打开文件,写入用户输入的文本。

以读取模式打开文件,读取内容并输出。

示例:

输入文本:"Hello, Python!"

输出:Hello, Python!

复制代码
# 题目2和题目4:文件写入与读取操作
def write_file_with_user_input(filename="user_input.txt"):
    """将用户输入的文本写入文件"""
    try:
        # 获取用户输入
        user_text = input("请输入要写入文件的文本:")
        
        # 使用with语句确保文件正确关闭
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(user_text)
        
        print(f"文本已成功写入文件:{filename}")
        
        # 读取并显示文件内容
        with open(filename, 'r', encoding='utf-8') as file:
            content = file.read()
        
        print(f"从文件读取的内容:{content}")
        return True
        
    except Exception as e:
        print(f"操作失败:{e}")
        return False

def write_file_with_fixed_content(filename="example.txt"):
    """将固定文本写入文件并读取(题目4)"""
    try:
        # 示例文本
        text = "Hello, Python!"
        
        # 写入文件
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(text)
        
        print(f"文本已写入文件:{filename}")
        
        # 读取文件
        with open(filename, 'r', encoding='utf-8') as file:
            content = file.read()
        
        print(f"读取的内容:{content}")
        return True
        
    except Exception as e:
        print(f"操作失败:{e}")
        return False

# 执行测试
if __name__ == "__main__":
    print("=== 测试题目2:用户输入写入文件 ===")
    # 为了方便测试,这里改为使用固定文本,实际使用时可以取消注释下面的行
    # write_file_with_user_input()
    
    # 使用固定文本进行演示
    with open("user_input.txt", 'w', encoding='utf-8') as f:
        f.write("这是一个测试文本")
    
    with open("user_input.txt", 'r', encoding='utf-8') as f:
        print(f"演示内容:{f.read()}")
    
    print("\n=== 测试题目4:固定文本写入文件 ===")
    write_file_with_fixed_content()

题目 5:选择题

以下哪个操作会导致文件被覆盖(如果文件已存在)?

A. 打开文件时使用模式'r'

B. 打开文件时使用模式'a'

C. 打开文件时使用模式'w'

D. 打开文件时使用模式'r+'
C. 打开文件时使用模式'w'

题目 6:简答题

简要说明文件模式'r'、'w'和'a'的区别,并举例说明它们的使用场景。
'r'(读取模式):以只读方式打开文件,如果文件不存在会抛出FileNotFoundError异常。适用于读取现有文件内容,如配置文件、日志分析等。

'w'(写入模式):以写入方式打开文件,如果文件存在会清空内容,不存在则创建新文件。适用于创建新文件或覆盖旧文件,如程序输出、数据导出等。

'a'(追加模式):以写入方式打开文件,但不会清空原有内容,新内容会被追加到文件末尾。如果文件不存在则创建新文件。适用于日志记录、数据累积存储等场景。

题目 7:编程题

编写一个Python程序,读取一个文本文件data.txt,统计文件中包含的行数、单词数和字符数,并输出结果。

提示: 可以使用readlines()方法读取文件的每一行。

复制代码
# 题目7:统计文件行数、单词数和字符数
import os

def count_file_stats(filename="data.txt"):
    """统计文件的行数、单词数和字符数"""
    try:
        # 如果文件不存在,先创建一个测试文件
        if not os.path.exists(filename):
            print(f"文件 {filename} 不存在,创建测试文件...")
            create_test_file(filename)
        
        # 初始化统计变量
        line_count = 0
        word_count = 0
        char_count = 0
        
        # 读取文件并统计
        with open(filename, 'r', encoding='utf-8') as file:
            for line in file:
                line_count += 1
                char_count += len(line)
                
                # 统计单词数(简单的空格分隔)
                words = line.strip().split()
                word_count += len(words)
        
        # 输出统计结果
        print(f"文件: {filename}")
        print(f"行数: {line_count}")
        print(f"单词数: {word_count}")
        print(f"字符数: {char_count}")
        
        return {
            'lines': line_count,
            'words': word_count,
            'chars': char_count
        }
        
    except FileNotFoundError:
        print(f"错误:文件 {filename} 不存在")
        return None
    except Exception as e:
        print(f"读取文件时发生错误:{e}")
        return None

def create_test_file(filename="data.txt"):
    """创建测试文件"""
    test_content = """Python is a powerful programming language.
It is widely used in data science, web development, and automation.
This is a test file for counting lines, words, and characters.
There are 4 lines in this file.
Each line contains several words.
The quick brown fox jumps over the lazy dog.
Hello World! 123 456 789."""
    
    with open(filename, 'w', encoding='utf-8') as file:
        file.write(test_content)
    
    print(f"测试文件 {filename} 已创建")

# 执行测试
if __name__ == "__main__":
    print("=== 测试题目7:文件内容统计 ===")
    stats = count_file_stats()
    
    if stats:
        print("\n统计完成!")

题目 8:选择题

以下哪个Python函数用于读取文件内容?

A. read()

B. write()

C. open()

D. close()
A. read()

题目 9:编程题

编写一个Python程序,检查一个文件是否存在。如果文件存在,则输出文件的内容;如果文件不存在,则输出文件不存在。

提示: 使用os.path.exists()来检查文件是否存在。

复制代码
# 题目9:检查文件是否存在并读取内容
import os

def check_file_and_read(filename="test.txt"):
    """检查文件是否存在,存在则读取内容,不存在则提示"""
    try:
        # 检查文件是否存在
        if os.path.exists(filename):
            print(f"文件 '{filename}' 存在,开始读取内容...")
            print("-" * 30)
            
            # 读取文件内容
            with open(filename, 'r', encoding='utf-8') as file:
                content = file.read()
            
            # 输出文件内容
            if content:
                print(content)
            else:
                print("文件内容为空")
            
            print("-" * 30)
            print(f"文件读取完成")
            return content
        else:
            print(f"文件 '{filename}' 不存在")
            return None
            
    except PermissionError:
        print(f"错误:没有权限读取文件 '{filename}'")
        return None
    except UnicodeDecodeError:
        print(f"错误:文件编码问题,无法读取文件 '{filename}'")
        return None
    except Exception as e:
        print(f"读取文件时发生错误:{e}")
        return None

def create_test_file_if_needed(filename="test.txt"):
    """如果需要,创建测试文件"""
    if not os.path.exists(filename):
        test_content = """这是一个测试文件。
用于演示文件存在性检查和读取功能。
本文件包含三行文本。
每行文本都以句号结束。"""
        
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(test_content)
        
        print(f"已创建测试文件: {filename}")
        return True
    return False

# 执行测试
if __name__ == "__main__":
    print("=== 测试题目9:文件存在性检查 ===")
    
    # 测试1:文件不存在的情况
    print("\n测试1:检查不存在的文件")
    check_file_and_read("non_existent_file.txt")
    
    # 测试2:文件存在的情况
    print("\n测试2:检查存在的文件")
    
    # 确保测试文件存在
    create_test_file_if_needed()
    
    # 检查并读取文件
    check_file_and_read()
    
    # 测试3:空文件
    print("\n测试3:检查空文件")
    empty_filename = "empty_test.txt"
    
    # 创建空文件
    with open(empty_filename, 'w', encoding='utf-8') as f:
        pass  # 创建空文件
    
    check_file_and_read(empty_filename)
    
    # 清理测试文件
    if os.path.exists(empty_filename):
        os.remove(empty_filename)
        print(f"\n已清理测试文件: {empty_filename}")

题目 10:选择题

在Python中,如何确保在文件操作后自动关闭文件,以避免文件句柄泄漏?

A. 使用open()函数时,手动调用close()

B. 使用with语句打开文件,自动关闭

C. 只需在操作完成后不再引用文件对象

D. 文件操作完毕后系统会自动关闭文件
B. 使用with语句打开文件,自动关闭

相关推荐
菜鸟233号11 分钟前
力扣416 分割等和子串 java实现
java·数据结构·算法·leetcode
belldeep11 分钟前
python:pyTorch 入门教程
pytorch·python·ai·torch
金融RPA机器人丨实在智能11 分钟前
深度拆解 RPA 机器人:定义、应用、价值与未来方向
人工智能·rpa·实在rpa
csbysj202012 分钟前
JSON.parse() 方法详解
开发语言
乐观主义现代人12 分钟前
redis 源码学习笔记
redis·笔记·学习
青主创享阁12 分钟前
技术破局农业利润困局:玄晶引擎AI数字化解决方案的架构设计与落地实践
大数据·人工智能
YJlio13 分钟前
Registry Usage (RU) 学习笔记(15.5):注册表内存占用体检与 Hive 体量分析
服务器·windows·笔记·python·学习·tcp/ip·django
奔波霸的伶俐虫14 分钟前
redisTemplate.opsForList()里面方法怎么用
java·开发语言·数据库·python·sql
datamonday15 分钟前
[EAI-037] π0.6* 基于RECAP方法与优势调节的自进化VLA机器人模型
人工智能·深度学习·机器人·具身智能·vla
Swift社区17 分钟前
LeetCode 469 凸多边形
算法·leetcode·职场和发展