osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

All of a sudden code started throwing errors


srinivasan wrote:

> Dear Python Experts
> 
> Could you please let me know why am I seeing the following errors as
> before this it was working consistently?

>     cwd = os.getcwd()
> FileNotFoundError: [Errno 2] No such file or directory
> root:~/qa/robot_tests#

Steps to reproduce the problem:

$ mkdir ~/foo
$ cd foo
$ python3.4
Python 3.4.3 (default, Nov 12 2018, 22:25:49) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.abspath(".")
'/home/peter/foo'
>>> os.rmdir("/home/peter/foo")
>>> os.path.abspath(".")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/posixpath.py", line 361, in abspath
    cwd = os.getcwd()
FileNotFoundError: [Errno 2] No such file or directory

Diagnosis: you managed to remove your current working directory, probably 
because you used os.chdir() to switch to a temporary directory and then 
forgot to switch back.

Solution: don't do that ;)

I recommend that you avoid chdir() in your code and instead always include 
the directory into the filename.