python-os

python os.walk to certain level [duplicate]

左心房为你撑大大i 提交于 2019-12-03 17:31:13
问题 This question already has answers here : Travel directory tree with limited recursion depth (2 answers) Closed 2 years ago . I want to build a program that uses some basic code to read through a folder and tell me how many files are in the folder. Here is how I do that currently: import os folders = ['Y:\\path1', 'Y:\\path2', 'Y:\\path3'] for stuff in folders: for root, dirs, files in os.walk(stuff, topdown=True): print("there are", len(files), "files in", root) This works great until there

Is it safe to use os.environ.setdefault?

和自甴很熟 提交于 2019-12-03 09:43:29
From my ipython shell, I see a method setdefault in os.environ but it is not documented. http://docs.python.org/library/os.html#os.environ . Is it documented somewhere else? def setdefault(self, key, failobj=None): if key not in self: self[key] = failobj return self[key] Can I use this function or write a wrapper for those lines? The os.environ documentation does state it's a mapping: A mapping object representing the string environment. As such it behaves according to the python mapping documentation of which dict is the standard implementation. os.environ therefor behaves just like the

Difference between os.getenv and os.environ.get

南楼画角 提交于 2019-11-28 15:12:36
问题 Is there any difference at all between both approaches? >>> os.getenv('TERM') 'xterm' >>> os.environ.get('TERM') 'xterm' >>> os.getenv('FOOBAR', "not found") == "not found" True >>> os.environ.get('FOOBAR', "not found") == "not found" True They seem to have the exact same functionality. 回答1: One difference observed (Python27): os.environ raises an exception if the environmental variable does not exist. os.getenv does not raise an exception, but returns None 回答2: See this related thread.