简介:在Python中,os库是处理操作系统相关功能的重要标准库之一。本文将详细介绍os库中的文件操作和路径操作,包括文件读写、文件属性获取、路径操作等。通过这些功能,我们可以更加方便地与操作系统进行交互,提高编程效率。
在Python中,os库提供了许多与操作系统交互的功能,包括文件操作和路径操作。下面我们将详细介绍os库中的文件操作和路径操作。
一、文件操作
import os# 打开文件,以写入模式打开,如果文件不存在则创建file = os.open('example.txt', os.O_WRONLY | os.O_CREAT)# 写入数据到文件os.write(file, b'Hello, world!')# 关闭文件os.close(file)
二、路径操作
import os# 获取文件大小file_size = os.path.getsize('example.txt')print(f'File size: {file_size} bytes')
import os# 获取当前工作目录current_directory = os.getcwd()print(f'Current directory: {current_directory}')
import os# 拼接路径path = os.path.join('folder', 'file.txt')print(f'Path: {path}')
import os# 判断路径是否为文件或目录path = 'folder/file.txt'if os.path.isfile(path):print(f'{path} is a file')elif os.path.isdir(path):print(f'{path} is a directory')else:print(f'{path} does not exist')