导入 os 库,用于与操作系统进行交互,例如管理文件和目录。
import os
# 获取当前工作目录"current working directory" 的缩写,表示当前工作目录
current_dir = os.getcwd()
print("当前工作目录:", current_dir)
# 获取文件的绝对路径
file_path = os.path.abspath("file.txt")
print("文件的绝对路径:", file_path)
# 获取文件所在的目录
file_dir = os.path.dirname(file_path)
print("文件所在的目录:", file_dir)
#列出指定目录下的文件和文件夹。
files = os.listdir(current_dir)
print(files)
# 拼接路径
new_path = os.path.join(file_dir, "subfolder", "new_file.txt")
print("拼接后的路径:", new_path)
os.makedirs()创建目录
dir_path = os.path.join('parent_dir', 'child_dir')
os.makedirs(dir_path) # 创建名为"parent_dir/child_dir"的多级目录
exist_ok
(可选参数):表示如果目录已经存在,是否报错。默认值为False
,即目录已存在时会引发FileExistsError
错误。如果设置为True
,则不会报错。
例子:
1.创建一个名为"data"的文件夹,如果已经存在则不会引发错误。将文件路径连接起来并命名为"data_file"。使用写入模式打开文件,并将其命名为"f"。
os.makedirs(os.path.join('..', 'data'), exist_ok=True)
data_file = os.path.join('..', 'data', 'house_tiny.csv')
with open(data_file, 'w') as f:
f.write('NumRooms,Alley,Price\n') # 列名
f.write('NA,Pave,127500\n') # 每行表示一个数据样本
f.write('2,NA,106000\n')