我遇到了麻烦。我有几个目录然后我需要cd到使用os.chdir。但是我在下一段代码中不断出现错误:
import os
new_folder = 'Zarazogic acid A'
os.chdir(new_folder)
FileNotFoundError: [Errno 2] No such file or directory: 'Zarazogic acid A'
我试图通过以下方式逃避角色:
new_directory = 'Zarazogic acid A'
new_directory = new_directory.replace(' ', '\ ')
os.chdir(new_directory)
FileNotFoundError: [Errno 2] No such file or directory: 'Zarazogi\\acid\\A'
试图用'\'甚至'\\'逃脱 - 仍然得到同样的错误。我该如何解决?
答案 0 :(得分:0)
这是一个简单的Python 3脚本(md23.py
),它表明目录不在您认为的位置。
#!/usr/bin/env python3
import os
new_folder = 'Zarazogic acid A'
print("0:", os.listdir('.'))
os.mkdir(new_folder)
print("1:", os.listdir('.'))
os.chdir(new_folder)
print("2:", os.listdir('.'))
os.chdir('..')
print("3:", os.listdir('.'))
os.rmdir(new_folder)
print("4:", os.listdir('.'))
它并不漂亮,但它适用于Python 3 - 您必须更改打印才能使其与Python 2一起使用。
当脚本位于其他空目录中时,输出为:
0: ['md23.py']
1: ['md23.py', 'Zarazogic acid A']
2: []
3: ['md23.py', 'Zarazogic acid A']
4: ['md23.py']
这表明该目录可以创建,列出,更改为,新目录为空,更改备份目录级别时仍然存在,并且可以将其删除。
你应该能够把它放在你当前的脚本旁边,并运行它,它应该成功。如果Zarazogic acid A
目录已存在,则会失败。例如,如果我在运行脚本之前创建目录,我会得到以下输出:
$ mkdir 'Zarazogic acid A'
$ python3 md23.py
0: ['md23.py', 'Zarazogic acid A']
Traceback (most recent call last):
File "md23.py", line 8, in <module>
os.mkdir(new_folder)
FileExistsError: [Errno 17] File exists: 'Zarazogic acid A'
$
变体脚本md29.py
,也打印了目录名称:
#!/usr/bin/env python2.7
import os
new_folder = 'Zarazogic acid A'
print "0:", os.getcwd(), os.listdir('.')
os.mkdir(new_folder)
print "1:", os.getcwd(), os.listdir('.')
os.chdir(new_folder)
print "2:", os.getcwd(), os.listdir('.')
os.chdir('..')
print "3:", os.getcwd(), os.listdir('.')
os.rmdir(new_folder)
print "4:", os.getcwd(), os.listdir('.')
示例运行:
0: /Users/jleffler/soq/junk ['md23.py', 'md29.py']
1: /Users/jleffler/soq/junk ['md23.py', 'md29.py', 'Zarazogic acid A']
2: /Users/jleffler/soq/junk/Zarazogic acid A []
3: /Users/jleffler/soq/junk ['md23.py', 'md29.py', 'Zarazogic acid A']
4: /Users/jleffler/soq/junk ['md23.py', 'md29.py']