头图

在Python中,文件操作是一项基本技能,而os库则提供了丰富的操作系统相关功能。以下是一些基本的文件操作和os库的使用:

文件操作

Python中的文件操作主要通过内建函数open()来进行。基本的操作包括读取、写入和关闭文件。

# 打开文件
file = open('example.txt', 'r')

# 读取文件
content = file.read()

# 写入文件
file = open('example.txt', 'w')
file.write('Hello, World!')

# 关闭文件
file.close()

os库

os库提供了许多操作系统相关的功能,如文件和目录操作。

import os

# 获取当前工作目录
cwd = os.getcwd()

# 改变当前工作目录
os.chdir('/path/to/directory')

# 创建目录
os.mkdir('new_directory')

# 删除文件
os.remove('example.txt')

# 列出目录内容
os.listdir(cwd)

以上仅为Python文件操作和os库的基本用法,实际使用中需要根据具体需求进行调整。


蓝易云
36 声望4 粉丝