Pyfakefs是否不支持os.renames?测试代码报错求助
问题分析与解决
pyfakefs是支持os.renames方法的,你遇到的FileNotFoundError大概率是路径拼接不规范导致的,也可能是使用的pyfakefs版本过旧对os.renames的支持不完善。
具体原因
你代码中手动用+和\\拼接路径,在Windows环境或pyfakefs的路径解析逻辑中可能出现格式错误(比如转义字符处理问题);另外旧版本pyfakefs对os.renames的递归路径处理存在bug。
解决步骤
用
os.path.join规范路径拼接
替换所有手动拼接路径的代码,改用os.path.join,它会自动适配不同系统的路径分隔符,避免格式错误。升级pyfakefs到最新版本
执行命令更新:pip install --upgrade pyfakefs pytest
修改后的测试代码
import os def move_all(firstPath, secondPath): for count, filename in enumerate(os.listdir(firstPath)): print(f'moving {count} {filename}') src_path = os.path.join(firstPath, filename) dst_path = os.path.join(secondPath, filename) os.renames(src_path, dst_path) def test_fakefs(fs): fakeDirectory = os.path.join('\\', 'fakeroot', 'fakefolder') fakeFile1 = 'fake_file.txt' fakeFile2 = 'fake_file_2.txt' target_dir = os.path.join('\\', 'fakeroot', 'fakefolder2') fs.create_dir(fakeDirectory) fs.create_file(os.path.join(fakeDirectory, fakeFile1)) fs.create_file(os.path.join(fakeDirectory, fakeFile2)) fs.create_dir(target_dir) move_all(fakeDirectory, target_dir) assert os.path.exists(os.path.join(target_dir, fakeFile1))
补充说明
os.renames和os.rename的核心区别是前者会递归创建目标路径的父目录(如果不存在),但你已经提前创建了目标目录,所以问题不在这。规范路径拼接后,结合最新版本的pyfakefs,就能解决报错问题。
内容的提问来源于stack exchange,提问作者Honkou
相关产品推荐
相关产品推荐

