程序员开发实例大全宝库

网站首页 > 编程文章 正文

Python 文件操作:你不可错过的学习资源

zazugpt 2024-09-28 03:55:33 编程文章 87 ℃ 0 评论

Python 文件操作是任何 Python 程序员必备的基本技能。掌握文件操作,可以让我们轻松完成数据读写、文件管理等任务。

本文列出一些帮助 Python 开发人员更深入地理解和掌握文件操作相关知识和技巧。

1. 读取文件

读取文件的全部内容:

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

2. 写入文件

要将文本写入文件并覆盖现有内容,执行以下操作:

with open('example.txt', 'w') as file:
    file.write('Hello, Python!')

3. 追加到文件

要将文本添加到现有文件的末尾,请执行以下操作:

with open('example.txt', 'a') as file:
    file.write('\nAppend this line.')

4. 将行读入列表

要将文件逐行读入列表中:

with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)

5. 遍历文件中的每一行

要处理文件中的每一行,请执行以下操作:

with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())

6. 检查文件是否存在

要在执行文件操作之前检查文件是否存在,请执行以下操作:

import os
if os.path.exists('example.txt'):
    print('File exists.')
else:
    print('File does not exist.')

7. 将列表写入文件

若要将列表的每个元素写入文件中的新行,请执行以下操作:

lines = ['First line', 'Second line', 'Third line']
with open('example.txt', 'w') as file:
    for line in lines:
        file.write(f'{line}\n')

8. 将 With 块用于多个文件

要使用块同时处理多个文件,执行以下操作:

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:
    content = source.read()
    destination.write(content)

9. 删除文件

要安全删除文件(如果存在):

import os
if os.path.exists('example.txt'):
    os.remove('example.txt')
    print('File deleted.')
else:
    print('File does not exist.')

10. 读取和写入二进制文件

要在二进制模式下读取和写入文件(对图像、视频等有用):

# Reading a binary file
with open('image.jpg', 'rb') as file:
    content = file.read()
# Writing to a binary file
with open('copy.jpg', 'wb') as file:
    file.write(content)

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表