zoukankan      html  css  js  c++  java
  • [Python] Pitfalls: Be Careful with os.chdir

    One thing you need to keep in mind is that when using os.chdir to change the working directory of current programme (script), make sure if we need to come back to the current working directory again.

    Using os.chdir to change the current working directory anywhere in the programme will effect permanently, regardless if you are using it in a function or not, see the following example:

     1 import os
     2 
     3 def chdir_in_func():
     4     print "Before chaning, in func"
     5     print os.getcwd()
     6     os.chdir("/home/")
     7     print "After chaning, in func"
     8     print os.getcwd()
     9 
    10 
    11 if __name__ == "__main__":
    12     print "Before changing, outside func"
    13     print os.getcwd()
    14     chdir_in_func()
    15     print "After changing, outside func"
    16     print os.getcwd()

    The output of this script will be:

    Before changing, outside func
    /home/chdir_in_func
    Before chaning, in func
    /home/chdir_in_func
    After chaning, in func
    /home
    After changing, outside func
    /home

    We can see that in the function, if we changes the directory, the current working directory is changed too.

    A suggested good practice to avoid such unconsciously mistake is that alway change back to your original working directory after the actions done in the new directory, unless you know you need to stay there for next operations. I would strongly recommend that in functions, if you have to change directory, always changes it back before returning:

    def func():
        cwd_save = os.getcwd()
        os.chdir(new_dir)
        # Actions in new_dir
        os.chdir(cwd_save)
        return True
  • 相关阅读:
    super.getClass().getName()方法调用的返回
    外观模式(Façade Pattern)
    Framework 4.0 将何去何从
    SQL Server 2005 第一篇 引言
    抽象工厂模式(Abstract Factory)
    浅谈分页技术
    垃圾邮件
    读书时的软件开发梦
    写技术博客的一个原因应该是寂寞吧
    当下10大最热门的网站开发技术
  • 原文地址:https://www.cnblogs.com/cheese-bacon/p/4150983.html
Copyright © 2011-2022 走看看