#!/usr/bin/env python3 """ 直接测试文件写入,绕过所有业务逻辑 """ import os def test_direct_write(): """直接测试文件写入""" print("=== 直接文件写入测试 ===") # 测试内容 test_content = b"Direct write test content - bypassing all logic" # 文件路径 file_path = "uploads/direct_test_write.txt" print(f"测试内容大小: {len(test_content)} bytes") print(f"目标路径: {os.path.abspath(file_path)}") # 确保目录存在 os.makedirs("uploads", exist_ok=True) # 方法1: 使用 open 直接写入 print("\n--- 方法1: 直接 open 写入 ---") try: with open(file_path, "wb") as f: written = f.write(test_content) f.flush() os.fsync(f.fileno()) print(f"写入字节数: {written}") if os.path.exists(file_path): size = os.path.getsize(file_path) print(f"文件大小: {size} bytes") if size == len(test_content): print("✅ 方法1成功!") else: print(f"❌ 方法1失败: 大小不匹配 {size} != {len(test_content)}") else: print("❌ 方法1失败: 文件不存在") except Exception as e: print(f"❌ 方法1异常: {e}") # 方法2: 使用 Path 写入 print("\n--- 方法2: 使用 pathlib.Path 写入 ---") from pathlib import Path file_path2 = "uploads/path_test_write.txt" try: Path(file_path2).write_bytes(test_content) if os.path.exists(file_path2): size = os.path.getsize(file_path2) print(f"文件大小: {size} bytes") if size == len(test_content): print("✅ 方法2成功!") else: print(f"❌ 方法2失败: 大小不匹配 {size} != {len(test_content)}") else: print("❌ 方法2失败: 文件不存在") except Exception as e: print(f"❌ 方法2异常: {e}") # 方法3: 检查现有文件 print("\n--- 方法3: 检查现有损坏的文件 ---") existing_files = [f for f in os.listdir("uploads") if f.endswith('.txt')] print(f"现有文本文件: {existing_files}") for filename in existing_files[:3]: # 只检查前3个 file_path = os.path.join("uploads", filename) try: size = os.path.getsize(file_path) print(f"{filename}: {size} bytes") if size > 0: with open(file_path, 'rb') as f: content = f.read(min(100, size)) print(f" 内容预览: {content}") except Exception as e: print(f" 读取错误: {e}") if __name__ == "__main__": test_direct_write()