Pathlib的is_file在回环挂载raw镜像上失效问题
Pathlib is_file() 在回环挂载镜像上返回False的问题
我在处理回环挂载的.raw镜像文件时,遇到了Pathlib的is_file()方法异常的问题:
- diff.txt中记录的文件路径对应挂载到/mnt/new下的镜像内文件
- 通过ls命令可以确认目标文件确实存在
- 但Python代码中调用is_file()始终返回False,调试输出也验证了这一点
验证步骤及输出
- 查看diff.txt中的目标文件路径:
cat diff.txt | grep kvm-recheck-rcu.sh usr/src/linux-hwe-6.5-headers-6.5.0-17/tools/testing/selftests/rcutorture/bin/kvm-recheck-rcu.sh
- 用ls确认文件存在:
ls /mnt/new/usr/src/linux-hwe-6.5-headers-6.5.0-17/tools/testing/selftests/rcutorture/bin/kvm-recheck-rcu.sh /mnt/new/usr/src/linux-hwe-6.5-headers-6.5.0-17/tools/testing/selftests/rcutorture/bin/kvm-recheck-rcu.sh
问题代码
#!/usr/bin/env python3 import pathlib import os size = 0 mount_point = pathlib.Path("/mnt/new") with open("/tmp/diff.txt", mode="r") as f: while True: line = f.readline() p = pathlib.Path(line) mounted_file = mount_point / p if "kvm-recheck-rcu.sh" in mounted_file.name: print(f"debug: {mounted_file}:{mounted_file.is_file()}") if mounted_file.is_file(): print(mounted_file) size = size + os.stat(str(mounted_file)) if not line: break print(size)
调试输出
debug: /mnt/new/usr/src/linux-hwe-6.5-headers-6.5.0-17/tools/testing/selftests/rcutorture/bin/kvm-recheck-rcu.sh :False
问题原因及解决方法
问题出在readline()读取的行末尾包含换行符\n,导致构建的Path对象路径末尾带有换行,实际对应的文件并不存在,因此is_file()返回False。
修改方法是读取行时去除换行符和首尾空白字符,同时修正原代码中文件大小累加的错误:
#!/usr/bin/env python3 import pathlib import os size = 0 mount_point = pathlib.Path("/mnt/new") with open("/tmp/diff.txt", mode="r") as f: while True: line = f.readline().strip() # 去除换行和首尾空白 if not line: # 处理空行(包括文件结束) break p = pathlib.Path(line) mounted_file = mount_point / p if "kvm-recheck-rcu.sh" in mounted_file.name: print(f"debug: {mounted_file}:{mounted_file.is_file()}") if mounted_file.is_file(): print(mounted_file) size += os.stat(str(mounted_file)).st_size # 累加文件大小的st_size字段 print(size)
内容的提问来源于stack exchange,提问作者bearrito
相关产品推荐
相关产品推荐

