我想在txt文件中列出Oasis_3_3D中的文件夹名称,但系统找不到该目录。
import os
start_path = '~/MLMI/m3ae/Oasis_3_3D'
if os.path.exists(start_path) and os.path.isdir(start_path):
folder_names = [d for d in os.listdir(start_path) if os.path.isdir(os.path.join(start_path, d))]
with open('folder_list.txt', 'w') as f:
for folder in folder_names:
f.write("%s\n" % folder)
print('Folders have been written to folder_list.txt.')
else:
print(f"The directory {start_path} does not exist.")
结果: 目录 ~/MLMI/m3ae/Oasis_3_3D 不存在。
如果我不使用if函数来检查,结果是[Errno 2]没有这样的文件或目录
但它正确存在于项目文件中。
这是由于波形符(“~”)造成的。 Python 将其视为常规符号。要扩展它,您应该使用 os.path.expanduser.
elebur@pc:~$ touch ~/test.txt
elebur@pc:~$ python3
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.exists("~/test.txt")
False
>>> os.path.exists(os.path.expanduser("~/test.txt"))
True