将当前工作目录修改为“d:"并验证,最后将当前工作目录恢复为原来目录
d:\bak>type d:\dtest.txt
a test
d:\bak>type btest.txt
something in bak
d:\bak>python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> temp_dir = os.getcwd()
>>> print(temp_dir)
d:\bak
>>> os.chdir('d:/')
>>> f=open("dtest.txt")
>>> f.readlines()
['a test']
>>> f.close()
>>> f=open("btest.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'btest.txt'
>>> os.chdir(temp_dir)
>>> f=open("btest.txt")
>>> f.readlines()
['something in bak']
>>> f.close()
>>> f=open("dtest.txt")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'dtest.txt'
>>>
出错的提示信息,就是验证过程