Python总结----OS操作及常见示例(五)
1、遍历目录并统计文件大小
1 import os 2 3 def get_directory_size(directory): 4 total_size = 0 5 for root, dirs, files in os.walk(directory): 6 for file in files: 7 file_path = os.path.join(root, file) 8 total_size += os.path.getsize(file_path) 9 return total_size 10 11 size = get_directory_size(".") 12 print("目录总大小 (字节):", size)
2、使用 os 模块或 pathlib 模块遍历目录,并将文件和目录分别存储到不同的列表中
1 import os 2 3 def list_files_and_dirs(root_dir): 4 files = [] 5 dirs = [] 6 7 for root, dir_names, file_names in os.walk(root_dir): 8 for dir_name in dir_names: 9 dirs.append(os.path.join(root, dir_name)) # 存储完整路径 10 for file_name in file_names: 11 files.append(os.path.join(root, file_name)) # 存储完整路径 12 13 return files, dirs 14 15 # 示例用法 16 root_directory = "." # 当前目录 17 files, directories = list_files_and_dirs(root_directory) 18 19 print("文件列表:") 20 for file in files: 21 print(file) 22 23 print("\n目录列表:") 24 for dir in directories: 25 print(dir)
3、将指定文件下所有文件合并到一个新文件中,同时排除文件名包含生产二字的文件名
1 import os 2 3 def merge_files_in_directory(input_dir, output_file): 4 """ 5 读取指定目录下的所有文件,并将内容合并到一个新文件中(排除文件名包含“生产”的文件) 6 7 Args: 8 input_dir (str): 要读取的目录路径 9 output_file (str): 合并后的输出文件路径 10 """ 11 # 检查目录是否存在 12 if not os.path.isdir(input_dir): 13 print(f"错误:目录 '{input_dir}' 不存在!") 14 return 15 16 # 创建输出文件(如果不存在) 17 with open(output_file, 'w', encoding='utf-8') as outfile: 18 # 遍历目录下的所有文件 19 for filename in os.listdir(input_dir): 20 file_path = os.path.join(input_dir, filename) 21 22 # 跳过子目录,只处理文件,并排除文件名包含“生产”的文件 23 if os.path.isfile(file_path) and "生产" not in filename: 24 try: 25 # 读取文件内容并写入输出文件 26 with open(file_path, 'r', encoding='utf-8') as infile: 27 outfile.write(f"=== 文件: {filename} ===\n") # 可选:添加文件名作为分隔 28 outfile.write(infile.read()) 29 outfile.write("\n\n") # 可选:添加换行分隔 30 print(f"已合并: {filename}") 31 except UnicodeDecodeError: 32 print(f"警告: {filename} 不是文本文件,已跳过") 33 except Exception as e: 34 print(f"错误: 处理 {filename} 时出错 - {e}") 35 else: 36 if "生产" in filename: 37 print(f"跳过(包含“生产”):{filename}") 38 39 print(f"\n所有文件已合并到: {output_file}") 40 41 # 示例用法 42 input_directory = "./input_files" # 替换为你的目录路径 43 output_file_path = "./merged_output.txt" # 合并后的文件路径 44 45 merge_files_in_directory(input_directory, output_file_path)
4、os.path.abspath(__file__)
获取当前脚本文件的绝对路径,无论脚本是如何被运行的。如果脚本路径是 ./project/script.py,且当前工作目录是 /home/user,结果可能是 /home/user/project/script.py。
用途:当脚本需要读取同目录下的配置文件或数据文件时,可以用它构建文件的绝对路径:
1 import os 2 config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
5、os.path.dirname(os.path.abspath(__file__))
获取当前脚本所在的目录的绝对路径,如果脚本路径是 /home/user/project/script.py,结果会是 /home/user/project。
用途:当脚本需要读取同目录下的其他文件(如配置文件、数据文件)时,可以用它构建文件的绝对路径:
1 import os 2 3 # 获取当前脚本所在目录 4 script_dir = os.path.dirname(os.path.abspath(__file__)) 5 6 # 拼接同级目录下的文件路径 7 config_path = os.path.join(script_dir, "config.json") 8 data_path = os.path.join(script_dir, "data", "input.csv")
6、os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
获取当前脚本所在目录的父目录的父目录(上两级目录)的绝对路径。如果脚本路径是 /home/user/project/src/script.py,结果会是 /home/user
用途:当需要访问脚本目录的上级或上上级目录中的文件时(如配置文件、共享资源):
1 import os 2 3 # 获取上两级目录(例如脚本在 /project/src/utils/script.py) 4 project_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) 5 6 # 拼接路径(如访问 /project/config/settings.json) 7 config_path = os.path.join(project_root, "config", "settings.json")
浙公网安备 33010602011771号