py day32 元组与os
元组操作
# 元组 (tuple) 有序,可重复,元素不可修改
print("迭代元组:")
my_tuple = ('a', 'b', 'c')
for item in my_tuple:print(item)# 字典 (dict) - 默认迭代时返回键 (keys)
print("迭代字典 (默认迭代键):")
my_dict = {'name': 'Alice', 'age': 30, 'city': 'Singapore'}
for key in my_dict:print(key)# 迭代字典的值 (values)
print("迭代字典的值:")
for value in my_dict.values():print(value)
# 迭代字典的键值对 (items)
print("迭代字典的键值对:")
for key, value in my_dict.items(): # items返还键值对方法很好用print(f"Key: {key}, Value: {value}")os模块操作
#os模块的操作
import os
os.getcwd()# get current working directory 获取当前工作目录的绝对路径
os.listdir()# list directory 获取当前工作目录下的文件列表
patha=r'C:\Users\YourUsername\Documents'
pathb='MyProjectData'
filepath = os.path.join(patha,pathb)
os.environ #包含所有环境变量
for variable_name,value in os.environ.items():print(f"{variable_name}{value}")
print(f"有{len(os.environ)}个变量")os.walk()目录树历遍函数
now_directory=os.getcwd()print(f"遍历当前目录{now_directory}")
for dirpath,dirname,filename in os.walk(now_directory):print(f"当前文件路径{dirpath}")print(f"当前目录下的子目录{dirname}")print(f"目录下的文件{filename}")