What is the difference between __str__ and __repr__?

Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex’s post: The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah) __repr__ goal is to be unambiguous __str__ goal is to be readable Container’s __str__ uses contained objects’ __repr__ Default implementation is … Read more

How do I list all files of a directory?

os.listdir() returns everything inside a directory — including both files and directories. os.path‘s isfile() can be used to only list files: from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] Alternatively, os.walk() yields two lists for each directory it visits — one for files and … Read more

Catch multiple exceptions in one line (except block)

From Python Documentation: An except clause may name multiple exceptions as a parenthesized tuple, for example except (IDontLikeYouException, YouAreBeingMeanException) as e: pass Or, for Python 2 only: except (IDontLikeYouException, YouAreBeingMeanException), e: pass Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does … Read more

How do I get the current time?

Use datetime: >>> import datetime >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 1, 6, 15, 8, 24, 78915) >>> print(now) 2009-01-06 15:08:24.789150 For just the clock time without the date: >>> now.time() datetime.time(15, 8, 24, 78915) >>> print(now.time()) 15:08:24.789150 To save typing, you can import the datetime object from the datetime module: >>> from datetime … Read more

techhipbettruvabetnorabahisbahis forumueduedueduedueduseduseduseduseduedus