一文掌握Python中的文件操作

Python为文件处理提供了一组通用的工具和函数,使得对文件执行各种操作相对简单。这些操作包括打开文件、阅读其内容、写入新数据、追加到现有文件等。

文件可以包含广泛的信息,从纯文本文档到图像、数据库、电子表格等。Python的文件处理功能旨在适应这些不同类型的数据,使其成为数据分析,数据操作和自动化等任务的强大工具。

打开和关闭文件

可以使用 open() 功能打开文件。它有两个参数:文件路径和模式。一旦你完成了一个文件,使用 close() 关闭它是很重要的。

模式:

  • 'r' :读取模式。允许您读取文件的内容。
  • 'w' :写入模式。允许您将数据写入文件。它将覆盖现有内容。
  • 'a' :追加模式。允许您将数据添加到现有文件的末尾。
  • 'b' :二进制模式。用于处理非文本文件,如图像或可执行文件。
  • 'x' :独家创作。创建一个新文件,但如果该文件已存在,则会引发错误。
# Opening a file for reading
file = open('example.txt', 'r')

# Opening a file for writing (creates a new file if it doesn't exist, and truncates if it does)
file = open('example.txt', 'w')

# Opening a file for appending (appends to the end of an existing file)
file = open('example.txt', 'a')

# Opening a file in binary mode
file = open('example.txt', 'rb')

# Closing a file
file.close()

读取文件

可以使用 read() 方法从文件中读取。它读取文件的全部内容,或者可以指定要读取的字节数。

file = open('example.txt', 'r')
content = file.read()  # Reads the entire file
line = file.readline()  # Reads a single line
lines = file.readlines()  # Reads all lines and returns a list
print(content)
file.close()

写入文件

可以使用 write() 方法写入文件。这将用新内容替换现有内容。

file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()

删除文件

如果想在不添加内容的情况下将内容添加到现有文件中,则可以在append模式下打开该文件并使用 write() 方法。

file = open('example.txt', 'a')
file.write('\nThis is an appended line.')
file.close()

使用二进制文件

二进制文件处理非文本文件,如图像,音频等。使用“rb”模式进行阅读,使用“rb”模式进行写入。

# Reading a binary file
with open('binary_file.jpg', 'rb') as file:
    content = file.read()

# Writing to a binary file
with open('new_binary_file.jpg', 'wb') as file:
    file.write(content)

使用with语句

with 语句会在您完成操作后自动关闭文件。

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)
# File is automatically closed here

文件位置

每当读或写一个文件,"光标"前进。可以使用 seek() 方法更改位置。

with open('example.txt', 'r') as file:
    content = file.read(10)  # Reads the first 10 characters
    file.seek(0)  # Move cursor back to the beginning
    content = file.read(10)  # Reads the next 10 characters

使用目录

Python的 os 模块提供了与文件系统交互的函数。

import os

# Create a directory
os.mkdir('my_directory')

# List files in a directory
files = os.listdir('my_directory')
print(files)

# Remove a file
os.remove('my_file.txt')

# Remove an empty directory
os.rmdir('my_directory')

使用os模块进行文件操作

os 模块提供各种文件操作。

import os

# Rename a file
os.rename('old_name.txt', 'new_name.txt')

# Get the current working directory
cwd = os.getcwd()

# Change the working directory
os.chdir('/path/to/directory')

# Check if a file exists
os.path.exists('file.txt')

相关文章

如何用python打开文件

针对上一篇文章中,python打印内存并保存的相关操作中使用了python创建文件,打开文件,写入文件等一系列的操作;今天我们来讲解一下如何用python打开文件。一、文件处理在 Python 中使用...

Python怎么运行py文件,编程入门指南

1.摘要本文使用以下四种方法运行py文件:①使用命令行运行py文件,具体为先切换到对应路径,再输入“python 文件名.py ”;②以PowerShell方式打开路径运行py文件,首先进入到py文件...

Python 中的文件操作详解

文件处理操作作为日常编程中的一个必要操作之一,无论是读取日志文件、配置文件、还是将爬虫数据输出成其他的文件,都是文件操作中不可或缺的一部分。Python作为目前比较流行的编程语言,也提供了强大的文件操...

5分钟掌握在Python中处理文件的8种基本操作

I在 Python 中处理文件是一项常见任务,Python 提供了几个内置函数和模块来帮助您读取、写入和操作文件。以下是在 Python 中处理文件时可以执行的一些基本操作:打开文件:您可以使用该函数...

Python 小白必看!文件读写超详细攻略

在 Python 编程学习中,文件读写是一项核心的基础技能,掌握它是深入探索 Python 应用领域的关键一步。下面将为大家详细介绍 Python 文件读写的相关知识。文件打开模式在 Python 中...