Datasets:
Tasks:
Text Retrieval
Modalities:
Text
Formats:
json
Sub-tasks:
document-retrieval
Languages:
English
Size:
1K - 10K
_id
stringlengths 1
4
| title
stringclasses 1
value | text
stringlengths 1
22.5k
|
---|---|---|
0 | Environment variables are accessed through [`os.environ`](https://docs.python.org/library/os.html#os.environ):<br><br>```python<br>import os<br>print(os.environ['HOME'])<br><br>```<br><br>To see a list of all environment variables:<br><br>```python<br>print(os.environ)<br><br>```<br><br>---<br><br>If a key is not present, attempting to access it will raise a `KeyError`. To avoid this:<br><br>```python<br># Returns `None` if the key doesn't exist<br>print(os.environ.get('KEY_THAT_MIGHT_EXIST'))<br><br># Returns `default_value` if the key doesn't exist<br>print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))<br><br># Returns `default_value` if the key doesn't exist<br>print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))<br>``` |
|
1 | ```python<br>import os<br>print(os.environ['HOME'])<br><br>``` |
|
2 | os.**environ**<br><br>A [mapping](https://docs.python.org/3/glossary.html#term-mapping) object where keys and values are strings that represent the process environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.<br>This mapping is captured the first time the [`os`](https://docs.python.org/3/library/os.html#module-os) module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in [`os.environ`](https://docs.python.org/3/library/os.html#os.environ), except for changes made by modifying [`os.environ`](https://docs.python.org/3/library/os.html#os.environ) directly.<br>This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3/library/os.html#os.putenv) will be called automatically when the mapping is modified.<br>On Unix, keys and values use [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding) and `'surrogateescape'` error handler. Use [`environb`](https://docs.python.org/3/library/os.html#os.environb) if you would like to use a different encoding.<br>On Windows, the keys are converted to uppercase. This also applies when getting, setting, or deleting an item. For example, `environ['monty'] = 'python'` maps the key `'MONTY'` to the value `'python'`.<br>**Note** <br>Calling [`putenv()`](https://docs.python.org/3/library/os.html#os.putenv) directly does not change [`os.environ`](https://docs.python.org/3/library/os.html#os.environ), so it’s better to modify [`os.environ`](https://docs.python.org/3/library/os.html#os.environ).<br>**Note** <br>On some platforms, including FreeBSD and macOS, setting `environ` may cause memory leaks. Refer to the system documentation for `putenv()`.<br>You can delete items in this mapping to unset environment variables. [`unsetenv()`](https://docs.python.org/3/library/os.html#os.unsetenv) will be called automatically when an item is deleted from [`os.environ`](https://docs.python.org/3/library/os.html#os.environ), and when one of the `pop()` or `clear()` methods is called.<br>*Changed in version 3.9:* Updated to support [**PEP 584**](https://peps.python.org/pep-0584/)’s merge (`|`) and update (`|=`) operators. |
|
3 | On Python ≥ 3.5, use [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir):<br><br>```python<br>from pathlib import Path<br>Path("/my/directory").mkdir(parents=True, exist_ok=True)<br><br>```<br><br>For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:<br><br>Try [`os.path.exists`](https://docs.python.org/library/os.path.html#os.path.exists), and consider [`os.makedirs`](https://docs.python.org/library/os.html#os.makedirs) for the creation.<br><br>```python<br>import os<br>if not os.path.exists(directory):<br> os.makedirs(directory)<br><br>```<br><br>As noted in comments and elsewhere, there's a race condition – if the directory is created between the `os.path.exists` and the `os.makedirs` calls, the `os.makedirs` will fail with an `OSError`. Unfortunately, blanket-catching `OSError` and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.<br><br>One option would be to trap the `OSError` and examine the embedded error code (see [Is there a cross-platform way of getting information from Python’s OSError](https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror)):<br><br>```python<br>import os, errno<br><br>try:<br> os.makedirs(directory)<br>except OSError as e:<br> if e.errno != errno.EEXIST:<br> raise<br><br>```<br><br>Alternatively, there could be a second `os.path.exists`, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.<br><br>Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.<br><br>Modern versions of Python improve this code quite a bit, both by exposing [`FileExistsError`](https://docs.python.org/3.3/library/exceptions.html?#FileExistsError) (in 3.3+)...<br><br>```python<br>try:<br> os.makedirs("path/to/directory")<br>except FileExistsError:<br> # directory already exists<br> pass<br>``` |
|
4 | ```python<br>from pathlib import Path<br>Path("/my/directory").mkdir(parents=True, exist_ok=True)<br><br>``` |
|
5 | Path.**mkdir**(*mode=0o777*, *parents=False*, *exist_ok=False*)<br><br>Create a new directory at this given path. If *mode* is given, it is combined with the process’s `umask` value to determine the file mode and access flags. If the path already exists, [`FileExistsError`](https://docs.python.org/3/library/exceptions.html#FileExistsError) is raised.<br>If *parents* is true, any missing parents of this path are created as needed; they are created with the default permissions without taking *mode* into account (mimicking the POSIX `mkdir -p` command).<br>If *parents* is false (the default), a missing parent raises [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError).<br>If *exist_ok* is false (the default), [`FileExistsError`](https://docs.python.org/3/library/exceptions.html#FileExistsError) is raised if the target directory already exists.<br>If *exist_ok* is true, [`FileExistsError`](https://docs.python.org/3/library/exceptions.html#FileExistsError) will not be raised unless the given path already exists in the file system and is not a directory (same behavior as the POSIX `mkdir -p` command).<br>*Changed in version 3.5:* The *exist_ok* parameter was added. |
|
6 | A **staticmethod** is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument.<br><br>A **classmethod**, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how `dict.fromkeys()`, a classmethod, returns an instance of the subclass when called on a subclass:<br><br>```python<br>>>> class DictSubclass(dict):<br>... def __repr__(self):<br>... return "DictSubclass"<br>...<br>>>> dict.fromkeys("abc")<br>{'a': None, 'c': None, 'b': None}<br>>>> DictSubclass.fromkeys("abc")<br>DictSubclass<br>>>><br>``` |
|
7 | ```python<br>>>> class DictSubclass(dict):<br>... def __repr__(self):<br>... return "DictSubclass"<br>...<br>>>> dict.fromkeys("abc")<br>{'a': None, 'c': None, 'b': None}<br>>>> DictSubclass.fromkeys("abc")<br>DictSubclass<br>>>><br>``` |
|
8 | @**classmethod**<br><br>Transform a method into a class method.<br>A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:<br><br>**`class** **C**:<br> @classmethod**def** f(cls, arg1, arg2): ...`<br><br>The `@classmethod` form is a function [decorator](https://docs.python.org/3/glossary.html#term-decorator) – see [Function definitions](https://docs.python.org/3/reference/compound_stmts.html#function) for details.<br>A class method can be called either on the class (such as `C.f()`) or on an instance (such as `C().f()`). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.<br>Class methods are different than C++ or Java static methods. If you want those, see [`staticmethod()`](https://docs.python.org/3/library/functions.html#staticmethod) in this section. For more information on class methods, see [The standard type hierarchy](https://docs.python.org/3/reference/datamodel.html#types).<br>*Changed in version 3.9:* Class methods can now wrap other [descriptors](https://docs.python.org/3/glossary.html#term-descriptor) such as [`property()`](https://docs.python.org/3/library/functions.html#property).<br>*Changed in version 3.10:* Class methods now inherit the method attributes (`__module__`, `__name__`, `__qualname__`, `__doc__` and `__annotations__`) and have a new `__wrapped__` attribute.<br>*Changed in version 3.11:* Class methods can no longer wrap other [descriptors](https://docs.python.org/3/glossary.html#term-descriptor) such as [`property()`](https://docs.python.org/3/library/functions.html#property).<br><br>Transform a method into a static method.<br>A static method does not receive an implicit first argument. To declare a static method, use this idiom:<br><br>class C:<br> @staticmethoddef f(arg1, arg2, argN): ...<br><br>The @staticmethod form is a function decorator – see Function definitions for details.<br>A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such as f()).<br>Static methods in Python are similar to those found in Java or C++. Also, see classmethod() for a variant that is useful for creating alternate class constructors.<br>Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:<br><br>def regular_function():<br> ...<br><br>class C:<br> method = staticmethod(regular_function)<br><br>For more information on static methods, see The standard type hierarchy.<br>Changed in version 3.10: Static methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__), have a new __wrapped__ attribute, and are now callable as regular functions. |
|
9 | [`DataFrame.iterrows`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows) is a generator which yields both the index and row (as a Series):<br><br>```python<br>import pandas as pd<br><br>df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})<br>df = df.reset_index() # make sure indexes pair with number of rows<br><br>for index, row in df.iterrows():<br> print(row['c1'], row['c2'])<br><br>```<br><br>```python<br>10 100<br>11 110<br>12 120<br>``` |
|
10 | ```python<br>import pandas as pd<br><br>df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})<br>df = df.reset_index() # make sure indexes pair with number of rows<br><br>for index, row in df.iterrows():<br> print(row['c1'], row['c2'])<br><br>``` |
|
11 | Iteration<br>The behavior of basic iteration over pandas objects depends on the type. When iterating over a Series, it is regarded as array-like, and basic iteration produces the values. DataFrames follow the dict-like convention of iterating over the “keys” of the objects.<br>In short, basic iteration (for i in object) produces:<br>Series: values<br>DataFrame: column labels<br>pandas objects also have the dict-like items() method to iterate over the (key, value) pairs.<br>To iterate over the rows of a DataFrame, you can use the following methods:<br>iterrows(): Iterate over the rows of a DataFrame as (index, Series) pairs. This converts the rows to Series objects, which can change the dtypes and has some performance implications.<br>itertuples(): Iterate over the rows of a DataFrame as namedtuples of the values. This is a lot faster than iterrows(), and is in most cases preferable to use to iterate over the values of a DataFrame.<br>Warning<br>Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided with one of the following approaches:<br>Look for a vectorized solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing, …<br>When you have a function that cannot work on the full DataFrame/Series at once, it is better to use apply() instead of iterating over the values. See the docs on function application.<br>If you need to do iterative manipulations on the values but performance is important, consider writing the inner loop with cython or numba. See the enhancing performance section for some examples of this approach.<br>Warning<br>You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect! |
|
12 | You can use a global variable within other functions by declaring it as `global` **within each function that assigns a value to it**:<br><br>```python<br>globvar = 0<br><br>def set_globvar_to_one():<br> global globvar # Needed to modify global copy of globvar<br> globvar = 1<br><br>def print_globvar():<br> print(globvar) # No need for global declaration to read value of globvar<br><br>set_globvar_to_one()<br>print_globvar() # Prints 1<br><br>```<br><br>Since it's unclear whether `globvar = 1` is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the `global` keyword.<br><br>See other answers if you want to share a global variable across modules.<br> |
|
13 | ```python<br>globvar = 0<br><br>def set_globvar_to_one():<br> global globvar # Needed to modify global copy of globvar<br> globvar = 1<br><br>def print_globvar():<br> print(globvar) # No need for global declaration to read value of globvar<br><br>set_globvar_to_one()<br>print_globvar() # Prints 1<br><br>``` |
|
14 | 7.12. The global statement<br>global_stmt ::= "global" identifier ("," identifier)*<br>The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.<br>Names listed in a global statement must not be used in the same code block textually preceding that global statement.<br>Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.<br>CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.<br>Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions. |
|
15 | [Decode the `bytes` object](https://docs.python.org/3/library/stdtypes.html#bytes.decode) to produce a string:<br><br>```python<br>>>> b"abcde".decode("utf-8")<br>'abcde'<br><br>```<br><br>The above example *assumes* that the `bytes` object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in! |
|
16 | ```python<br>>>> b"abcde".decode("utf-8")<br>'abcde'<br><br>``` |
|
17 | bytes.**decode**(*encoding='utf-8'*, *errors='strict'*)<br><br>bytearray.**decode**(*encoding='utf-8'*, *errors='strict'*)<br><br>Return the bytes decoded to a [`str`](https://docs.python.org/3/library/stdtypes.html#str).<br>*encoding* defaults to `'utf-8'`; see [Standard Encodings](https://docs.python.org/3/library/codecs.html#standard-encodings) for possible values.<br>*errors* controls how decoding errors are handled. If `'strict'` (the default), a [`UnicodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeError) exception is raised. Other possible values are `'ignore'`, `'replace'`, and any other name registered via [`codecs.register_error()`](https://docs.python.org/3/library/codecs.html#codecs.register_error). See [Error Handlers](https://docs.python.org/3/library/codecs.html#error-handlers) for details.<br>For performance reasons, the value of *errors* is not checked for validity unless a decoding error actually occurs, [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode) is enabled or a [debug build](https://docs.python.org/3/using/configure.html#debug-build) is used.<br>**Note** <br>Passing the *encoding* argument to [`str`](https://docs.python.org/3/library/stdtypes.html#str) allows decoding any [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) directly, without needing to make a temporary `bytes` or `bytearray` object.<br>*Changed in version 3.1:* Added support for keyword arguments.<br>*Changed in version 3.9:* The value of the *errors* argument is now checked in [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode) and in [debug mode](https://docs.python.org/3/using/configure.html#debug-build). |
|
18 | Use [`datetime`](https://docs.python.org/3/library/datetime.html):<br><br>```python<br>>>> import datetime<br>>>> now = datetime.datetime.now()<br>>>> now<br>datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)<br>>>> print(now)<br>2009-01-06 15:08:24.789150<br><br>```<br><br>For just the clock time without the date:<br><br>```python<br>>>> now.time()<br>datetime.time(15, 8, 24, 78915)<br>>>> print(now.time())<br>15:08:24.789150<br><br>```<br><br>---<br><br>To save typing, you can import the `datetime` object from the [`datetime`](https://docs.python.org/3/library/datetime.html) module:<br><br>```python<br>>>> from datetime import datetime<br><br>```<br><br>Then remove the prefix `datetime.` from all of the above. |
|
19 | ```python<br>>>> import datetime<br>>>> now = datetime.datetime.now()<br>>>> now<br>datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)<br>>>> print(now)<br>2009-01-06 15:08:24.789150<br><br>``` |
|
20 | datetime — Basic date and time types<br>Source code: Lib/datetime.py<br>The datetime module supplies classes for manipulating dates and times.<br>While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.<br>Aware and Naive Objects<br>Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.<br><br>With sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, an aware object can locate itself relative to other aware objects. An aware object represents a specific moment in time that is not open to interpretation. [1]<br>A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.<br>For applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo, that can be set to an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether daylight saving time is in effect.<br>Only one concrete tzinfo class, the timezone class, is supplied by the datetime module. The timezone class can represent simple timezones with fixed offsets from UTC, such as UTC itself or North American EST and EDT timezones. Supporting timezones at deeper levels of detail is up to the application. The rules for time adjustment across the world are more political than rational, change frequently, and there is no standard suitable for every application aside from UTC.<br>Available Types<br>class datetime.date<br>An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month, and day.<br><br>class datetime.time<br>An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond, and tzinfo.<br><br>class datetime.datetime<br>A combination of a date and a time. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo. |
|
21 | From [Python Documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions):<br><br>> An except clause may name multiple exceptions as a parenthesized tuple, for example<br>> <br><br>```python<br>except (IDontLikeYouException, YouAreBeingMeanException) as e:<br> pass<br><br>```<br><br>Or, for Python 2 only:<br><br>```python<br>except (IDontLikeYouException, YouAreBeingMeanException), e:<br> pass<br><br>```<br><br>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 not work in Python 3; now you should be using `as`. |
|
22 | ```python<br>except (IDontLikeYouException, YouAreBeingMeanException) as e:<br> pass<br><br>``` |
|
23 | Handling Exceptions<br>A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:<br>... except (RuntimeError, TypeError, NameError):<br>... pass |
|
24 | [`shutil`](http://docs.python.org/3/library/shutil.html) has many methods you can use. One of which is:<br><br>```python<br>import shutil<br><br>shutil.copyfile(src, dst)<br><br># 2nd option<br>shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp<br><br>```<br><br>- Copy the contents of the file named `src` to a file named `dst`. Both `src` and `dst` need to be the entire filename of the files, including path.<br>- The destination location must be writable; otherwise, an `IOError` exception will be raised.<br>- If `dst` already exists, it will be replaced.<br>- Special files such as character or block devices and pipes cannot be copied with this function.<br>- With `copy`, `src` and `dst` are path names given as `str`s.<br><br>Another `shutil` method to look at is [`shutil.copy2()`](https://docs.python.org/3/library/shutil.html#shutil.copy2). It's similar but preserves more metadata (e.g. time stamps).<br><br>If you use `os.path` operations, use `copy` rather than `copyfile`. `copyfile` will only accept strings. |
|
25 | ```python<br>import shutil<br><br>shutil.copyfile(src, dst)<br><br># 2nd option<br>shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp<br><br>``` |
|
26 | shutil — High-level file operations<br>Source code: Lib/shutil.py<br><br>The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module.<br>shutil.copyfile(src, dst, *, follow_symlinks=True)<br>Copy the contents (no metadata) of the file named src to a file named dst and return dst in the most efficient way possible. src and dst are path-like objects or path names given as strings.<br><br>dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.<br><br>The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function.<br><br>If follow_symlinks is false and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.<br><br>Raises an auditing event shutil.copyfile with arguments src, dst.<br><br>Changed in version 3.3: IOError used to be raised instead of OSError. Added follow_symlinks argument. Now returns dst.<br><br>Changed in version 3.4: Raise SameFileError instead of Error. Since the former is a subclass of the latter, this change is backward compatible.<br><br>Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section. |
|
27 | Use the [`in` operator](https://docs.python.org/reference/expressions.html#membership-test-details):<br><br>```python<br>if "blah" not in somestring:<br> continue<br><br>```<br><br>Note: This is case-sensitive. |
|
28 | ```python<br>if "blah" not in somestring:<br> continue<br><br>``` |
|
29 | 6.10.2. Membership test operations<br>The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).<br><br>For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.<br><br>For user-defined classes which define the __contains__() method, x in y returns True if y.__contains__(x) returns a true value, and False otherwise.<br><br>For user-defined classes which do not define __contains__() but do define __iter__(), x in y is True if some value z, for which the expression x is z or x == z is true, is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception.<br><br>Lastly, the old-style iteration protocol is tried: if a class defines __getitem__(), x in y is True if and only if there is a non-negative integer index i such that x is y[i] or x == y[i], and no lower integer index raises the IndexError exception. (If any other exception is raised, it is as if in raised that exception).<br><br>The operator not in is defined to have the inverse truth value of in. |
|
30 | ## Best practice<br><br>First, check if the file or folder exists and then delete it. You can achieve this in two ways:<br><br>1. `os.path.isfile("/path/to/file")`<br>2. Use `exception handling.`<br><br>**EXAMPLE** for `os.path.isfile`<br><br>```python<br>#!/usr/bin/python<br>import os<br><br>myfile = "/tmp/foo.txt"<br># If file exists, delete it.<br>if os.path.isfile(myfile):<br> os.remove(myfile)<br>else:<br> # If it fails, inform the user.<br> print("Error: %s file not found" % myfile)<br><br>```<br><br>### Exception Handling<br><br>```python<br>#!/usr/bin/python<br>import os<br><br># Get input.<br>myfile = raw_input("Enter file name to delete: ")<br><br># Try to delete the file.<br>try:<br> os.remove(myfile)<br>except OSError as e:<br> # If it fails, inform the user.<br> print("Error: %s - %s." % (e.filename, e.strerror))<br><br>```<br><br>### Respective output<br><br>```<br>Enter file name to delete : demo.txt<br>Error: demo.txt - No such file or directory.<br><br>Enter file name to delete : rrr.txt<br>Error: rrr.txt - Operation not permitted.<br><br>Enter file name to delete : foo.txt<br><br>```<br><br>### Python syntax to delete a folder<br><br>```python<br>shutil.rmtree()<br><br>```<br><br>Example for `shutil.rmtree()`<br><br>```python<br>#!/usr/bin/python<br>import os<br>import sys<br>import shutil<br><br># Get directory name<br>mydir = raw_input("Enter directory name: ")<br><br># Try to remove the tree; if it fails, throw an error using try...except.<br>try:<br> shutil.rmtree(mydir)<br>except OSError as e:<br> print("Error: %s - %s." % (e.filename, e.strerror))<br>``` |
|
31 | ```python<br>#!/usr/bin/python<br>import os<br>import sys<br>import shutil<br><br># Get directory name<br>mydir = raw_input("Enter directory name: ")<br><br># Try to remove the tree; if it fails, throw an error using try...except.<br>try:<br> shutil.rmtree(mydir)<br>except OSError as e:<br> print("Error: %s - %s." % (e.filename, e.strerror))<br>``` |
|
32 | shutil.**rmtree**(*path*, *ignore_errors=False*, *onerror=None*, ***, *onexc=None*, *dir_fd=None*)<br><br>Delete an entire directory tree; *path* must point to a directory (but not a symbolic link to a directory). If *ignore_errors* is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by *onexc* or *onerror* or, if both are omitted, exceptions are propagated to the caller.<br>This function can support [paths relative to directory descriptors](https://docs.python.org/3/library/os.html#dir-fd).<br>**Note** <br>On platforms that support the necessary fd-based functions a symlink attack resistant version of [`rmtree()`](https://docs.python.org/3/library/shutil.html#shutil.rmtree) is used by default. On other platforms, the [`rmtree()`](https://docs.python.org/3/library/shutil.html#shutil.rmtree) implementation is susceptible to a symlink attack: given proper timing and circumstances, attackers can manipulate symlinks on the filesystem to delete files they wouldn’t be able to access otherwise. Applications can use the [`rmtree.avoids_symlink_attacks`](https://docs.python.org/3/library/shutil.html#shutil.rmtree.avoids_symlink_attacks) function attribute to determine which case applies.<br>If *onexc* is provided, it must be a callable that accepts three parameters: *function*, *path*, and *excinfo*.<br>The first parameter, *function*, is the function which raised the exception; it depends on the platform and implementation. The second parameter, *path*, will be the path name passed to *function*. The third parameter, *excinfo*, is the exception that was raised. Exceptions raised by *onexc* will not be caught.<br>The deprecated *onerror* is similar to *onexc*, except that the third parameter it receives is the tuple returned from [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info).<br>Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `shutil.rmtree` with arguments `path`, `dir_fd`.<br>*Changed in version 3.3:* Added a symlink attack resistant version that is used automatically if platform supports fd-based functions.<br>*Changed in version 3.8:* On Windows, will no longer delete the contents of a directory junction before removing the junction.<br>*Changed in version 3.11:* Added the *dir_fd* parameter.<br>*Changed in version 3.12:* Added the *onexc* parameter, deprecated *onerror*. |
|
33 | ```python<br>if not a:<br> print("List is empty")<br><br>```<br><br>Using the [implicit booleanness](https://docs.python.org/library/stdtypes.html#truth-value-testing) of the empty `list` is quite Pythonic. |
|
34 | ```python<br>if not a:<br> print("List is empty")<br><br>``` |
|
35 | Built-in Types<br>The following sections describe the standard types that are built into the interpreter.<br><br>The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.<br><br>Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.<br><br>Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function). The latter function is implicitly used when an object is written by the print() function.<br><br>Truth Value Testing<br>Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.<br><br>By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. [1] Here are most of the built-in objects considered false:<br><br>constants defined to be false: None and False<br><br>zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)<br><br>empty sequences and collections: '', (), [], {}, set(), range(0)<br><br>Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)<br><br>Boolean Operations — and, or, not<br>These are the Boolean operations, ordered by ascending priority:<br><br>Operation<br><br>Result<br><br>Notes<br><br>x or y<br><br>if x is true, then x, else y<br><br>(1)<br><br>x and y<br><br>if x is false, then x, else y<br><br>(2)<br><br>not x<br><br>if x is false, then True, else False<br><br>(3)<br><br>Notes:<br><br>This is a short-circuit operator, so it only evaluates the second argument if the first one is false.<br><br>This is a short-circuit operator, so it only evaluates the second argument if the first one is true.<br><br>not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error. |
|
36 | If the reason you're checking is so you can do something like `if file_exists: open_it()`, it's safer to use a `try` around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.<br><br>If you're not planning to open the file immediately, you can use [`os.path.isfile`](https://docs.python.org/library/os.path.html#os.path.isfile) if you need to be sure it's a file.<br><br>> Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.<br>> <br><br>```python<br>import os.path<br>os.path.isfile(fname)<br>``` |
|
37 | ```python<br>import os.path<br>os.path.isfile(fname)<br>``` |
|
38 | os.path.**isfile**(*path*)<br><br>Return `True` if *path* is an [`existing`](https://docs.python.org/3/library/os.path.html#os.path.exists) regular file. This follows symbolic links, so both [`islink()`](https://docs.python.org/3/library/os.path.html#os.path.islink) and [`isfile()`](https://docs.python.org/3/library/os.path.html#os.path.isfile) can be true for the same path.<br>*Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). |
|
39 | Use the `+` operator to combine the lists:<br><br>```python<br>listone = [1, 2, 3]<br>listtwo = [4, 5, 6]<br><br>joinedlist = listone + listtwo<br><br>```<br><br>Output:<br><br>```python<br>>>> joinedlist<br>[1, 2, 3, 4, 5, 6]<br><br>```<br><br>NOTE: This will create a new list with a shallow copy of the items in the first list, followed by a shallow copy of the items in the second list. Use [copy.deepcopy()](https://docs.python.org/3/library/copy.html#copy.deepcopy) to get deep copies of lists. |
|
40 | ```python<br>listone = [1, 2, 3]<br>listtwo = [4, 5, 6]<br><br>joinedlist = listone + listtwo<br><br>```<br><br>Output:<br><br>```python<br>>>> joinedlist<br>[1, 2, 3, 4, 5, 6]<br><br>``` |
|
41 | copy.**deepcopy**(*x*[, *memo*])Return a deep copy of *x*.<br><br>*exception* copy.**Error**Raised for module specific errors.<br><br>The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):<br><br>- A *shallow copy* constructs a new compound object and then (to the extent possible) inserts *references* into it to the objects found in the original.<br>- A *deep copy* constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original.<br><br>Two problems often exist with deep copy operations that don’t exist with shallow copy operations:<br><br>- Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.<br>- Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.<br><br>The [`deepcopy()`](https://docs.python.org/3/library/copy.html#copy.deepcopy) function avoids these problems by:<br><br>- keeping a `memo` dictionary of objects already copied during the current copying pass; and<br>- letting user-defined classes override the copying operation or the set of components copied.<br><br>This module does not copy types like module, method, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) module.<br><br>Shallow copies of dictionaries can be made using [`dict.copy()`](https://docs.python.org/3/library/stdtypes.html#dict.copy), and of lists by assigning a slice of the entire list, for example, `copied_list = original_list[:]`.<br><br>Classes can use the same interfaces to control copying that they use to control pickling. See the description of module [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) for information on these methods. In fact, the [`copy`](https://docs.python.org/3/library/copy.html#module-copy) module uses the registered pickle functions from the [`copyreg`](https://docs.python.org/3/library/copyreg.html#module-copyreg) module.<br><br>In order for a class to define its own copy implementation, it can define special methods `__copy__()` and `__deepcopy__()`. The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the `memo` dictionary. If the `__deepcopy__()` implementation needs to make a deep copy of a component, it should call the [`deepcopy()`](https://docs.python.org/3/library/copy.html#copy.deepcopy) function with the component as first argument and the memo dictionary as second argument. The memo dictionary should be treated as an opaque object.<br><br>**See also**<br><br>**Module [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle)**Discussion of the special methods used to support object state retrieval and restoration. |
|
42 | [`figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html) tells you the call signature:<br><br>```python<br>from matplotlib.pyplot import figure<br><br>figure(figsize=(8, 6), dpi=80)<br><br>```<br><br>`figure(figsize=(1,1))` would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument. |
|
43 | ```python<br>from matplotlib.pyplot import figure<br><br>figure(figsize=(8, 6), dpi=80)<br><br>``` |
|
44 | # matplotlib.pyplot.figure<br><br>**matplotlib.pyplot.figure(*num=None*, *figsize=None*, *dpi=None*, ***, *facecolor=None*, *edgecolor=None*, *frameon=True*, *FigureClass=<class 'matplotlib.figure.Figure'>*, *clear=False*, ***kwargs*)[[source]](https://github.com/matplotlib/matplotlib/blob/v3.9.1/lib/matplotlib/pyplot.py#L870-L1056)**Create a new figure, or activate an existing figure. |
|
45 | There is also the [Python termcolor module](http://pypi.python.org/pypi/termcolor). Usage is pretty simple:<br><br>```python<br>from termcolor import colored<br><br>print(colored('hello', 'red'), colored('world', 'green'))<br><br>```<br><br>It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...<br><br>To get the ANSI codes working on windows, first run<br><br>```python<br>os.system('color')<br>``` |
|
46 | ```python<br>from termcolor import colored<br><br>print(colored('hello', 'red'), colored('world', 'green'))<br><br>``` |
|
47 | ## **Installation**<br><br>### **From PyPI**<br><br>```<br>python3 -m pip install --upgrade termcolor<br><br>```<br><br>### **From source**<br><br>```<br>git clone https://github.com/termcolor/termcolor<br>cd termcolor<br>python3 -m pip install .<br><br>```<br><br>### **Demo**<br><br>To see demo output, run:<br><br>```<br>python3 -m termcolor<br><br>```<br><br>## **Example**<br><br>```<br>import sys<br><br>from termcolor import colored, cprint<br><br>text = colored("Hello, World!", "red", attrs=["reverse", "blink"])<br>print(text)<br>cprint("Hello, World!", "green", "on_red")<br><br>print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan")<br>print_red_on_cyan("Hello, World!")<br>print_red_on_cyan("Hello, Universe!")<br><br>for i in range(10):<br> cprint(i, "magenta", end=" ")<br><br>cprint("Attention!", "red", attrs=["bold"], file=sys.stderr)<br><br>```<br><br>## **Text properties**<br><br>| Text colors | Text highlights | Attributes |<br>| --- | --- | --- |<br>| black | on_black | bold |<br>| red | on_red | dark |<br>| green | on_green | underline |<br>| yellow | on_yellow | blink |<br>| blue | on_blue | reverse |<br>| magenta | on_magenta | concealed |<br>| cyan | on_cyan | |<br>| white | on_white | |<br>| light_grey | on_light_grey | |<br>| dark_grey | on_dark_grey | |<br>| light_red | on_light_red | |<br>| light_green | on_light_green | |<br>| light_yellow | on_light_yellow | |<br>| light_blue | on_light_blue | |<br>| light_magenta | on_light_magenta | |<br>| light_cyan | on_light_cyan | | |
|
48 | [`.append()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) appends a **single object** at the end of the list:<br><br>```python<br>>>> x = [1, 2, 3]<br>>>> x.append([4, 5])<br>>>> print(x)<br>[1, 2, 3, [4, 5]]<br><br>```<br><br>[`.extend()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) appends **multiple objects** that are taken from inside the specified iterable:<br><br>```python<br>>>> x = [1, 2, 3]<br>>>> x.extend([4, 5])<br>>>> print(x)<br>[1, 2, 3, 4, 5]<br>``` |
|
49 | ```python<br>>>> x = [1, 2, 3]<br>>>> x.append([4, 5])<br>>>> print(x)<br>[1, 2, 3, [4, 5]]<br><br>```<br><br>```python<br>>>> x = [1, 2, 3]<br>>>> x.extend([4, 5])<br>>>> print(x)<br>[1, 2, 3, 4, 5]<br>``` |
|
50 | | s.append(x) | appends x to the end of the sequence (same as s[len(s):len(s)] = [x]) |<br>| --- | --- |<br><br>| s.extend(t) or s += t | extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t) |<br>| --- | --- | |
|
51 | To get the full path to the directory a Python file is contained in, write this in that file:<br><br>```python<br>import os<br>dir_path = os.path.dirname(os.path.realpath(__file__))<br><br>```<br><br>(Note that the incantation above won't work if you've already used `os.chdir()` to change your current working directory, since the value of the `__file__` constant is relative to the current working directory and is not changed by an `os.chdir()` call.)<br><br>---<br><br>To get the current working directory use<br><br>```python<br>import os<br>cwd = os.getcwd()<br><br>```<br><br>---<br><br>Documentation references for the modules, constants and functions used above:<br><br>- The [`os`](https://docs.python.org/library/os.html) and [`os.path`](https://docs.python.org/library/os.path.html#module-os.path) modules.<br>- The [`__file__`](https://docs.python.org/reference/datamodel.html) constant<br>- [`os.path.realpath(path)`](https://docs.python.org/library/os.path.html#os.path.realpath) (returns *"the canonical path of the specified filename, eliminating any symbolic links encountered in the path"*)<br>- [`os.path.dirname(path)`](https://docs.python.org/library/os.path.html#os.path.dirname) (returns *"the directory name of pathname `path`"*)<br>- [`os.getcwd()`](https://docs.python.org/library/os.html#os.getcwd) (returns *"a string representing the current working directory"*)<br>- [`os.chdir(path)`](https://docs.python.org/library/os.html#os.chdir) (*"change the current working directory to `path`"*) |
|
52 | ```python<br>import os<br>dir_path = os.path.dirname(os.path.realpath(__file__))<br><br>``` |
|
53 | os.path.**dirname**(*path*)<br><br>Return the directory name of pathname *path*. This is the first element of the pair returned by passing *path* to the function [`split()`](https://docs.python.org/3/library/os.path.html#os.path.split).<br>*Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). |
|
54 | ## Rename Specific Columns<br><br>Use the [`df.rename()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html) function and refer the columns to be renamed. Not all the columns have to be renamed:<br><br>```python<br>df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})<br><br># Or rename the existing DataFrame (rather than creating a copy)<br>df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)<br><br>```<br><br>**Minimal Code Example**<br><br>```python<br>df = pd.DataFrame('x', index=range(3), columns=list('abcde'))<br>df<br><br> a b c d e<br>0 x x x x x<br>1 x x x x x<br>2 x x x x x<br><br>```<br><br>The following methods all work and produce the same output:<br><br>```python<br>df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1)<br>df2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')<br>df2 = df.rename(columns={'a': 'X', 'b': 'Y'})<br><br>df2<br><br> X Y c d e<br>0 x x x x x<br>1 x x x x x<br>2 x x x x x<br><br>```<br><br>Remember to assign the result back, as the modification is not-inplace. Alternatively, specify `inplace=True`:<br><br>```python<br>df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)<br>df<br><br> X Y c d e<br>0 x x x x x<br>1 x x x x x<br>2 x x x x x<br><br>```<br><br>You can specify `errors='raise'` to raise errors if an invalid column-to-rename is specified. |
|
55 | ```python<br>df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})<br><br># Or rename the existing DataFrame (rather than creating a copy)<br>df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)<br><br>``` |
|
56 | # pandas.DataFrame.rename<br><br>**DataFrame.rename(*mapper=None*, ***, *index=None*, *columns=None*, *axis=None*, *copy=None*, *inplace=False*, *level=None*, *errors='ignore'*)[[source]](https://github.com/pandas-dev/pandas/blob/v2.2.2/pandas/core/frame.py#L5636-L5776)**Rename columns or index labels.<br>Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error. |
|
57 | To delete a key regardless of whether it is in the dictionary, use the two-argument form of [`dict.pop()`](http://docs.python.org/library/stdtypes.html#dict.pop):<br><br>```python<br>my_dict.pop('key', None)<br><br>```<br><br>This will return `my_dict[key]` if `key` exists in the dictionary, and `None` otherwise. If the second parameter is not specified (i.e. `my_dict.pop('key')`) and `key` does not exist, a `KeyError` is raised.<br><br>To delete a key that is guaranteed to exist, you can also use<br><br>```python<br>del my_dict['key']<br><br>```<br><br>This will raise a `KeyError` if the key is not in the dictionary. |
|
58 | ```python<br>my_dict.pop('key', None)<br><br>``` |
|
59 | **pop**(*key*[, *default*])<br><br>If *key* is in the dictionary, remove it and return its value, else return *default*. If *default* is not given and *key* is not in the dictionary, a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) is raised. |
|
60 | The [`sorted()`](https://docs.python.org/library/functions.html#sorted) function takes a `key=` parameter<br><br>```python<br>newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])<br><br>```<br><br>Alternatively, you can use [`operator.itemgetter`](https://docs.python.org/library/operator.html#operator.itemgetter) instead of defining the function yourself<br><br>```python<br>from operator import itemgetter<br>newlist = sorted(list_to_be_sorted, key=itemgetter('name'))<br><br>```<br><br>For completeness, add `reverse=True` to sort in descending order<br><br>```python<br>newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)<br>``` |
|
61 | ```python<br>newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])<br><br>``` |
|
62 | **sorted**(*iterable*, */*, ***, *key=None*, *reverse=False*)<br><br>Return a new sorted list from the items in *iterable*.<br>Has two optional arguments which must be specified as keyword arguments.<br>*key* specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). The default value is `None` (compare the elements directly).<br>*reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed.<br>Use [`functools.cmp_to_key()`](https://docs.python.org/3/library/functools.html#functools.cmp_to_key) to convert an old-style *cmp* function to a *key* function.<br>The built-in [`sorted()`](https://docs.python.org/3/library/functions.html#sorted) function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).<br>The sort algorithm uses only `<` comparisons between items. While defining an [`__lt__()`](https://docs.python.org/3/reference/datamodel.html#object.__lt__) method will suffice for sorting, [**PEP 8**](https://peps.python.org/pep-0008/) recommends that all six [rich comparisons](https://docs.python.org/3/reference/expressions.html#comparisons) be implemented. This will help avoid bugs when using the same data with other ordering tools such as [`max()`](https://docs.python.org/3/library/functions.html#max) that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the [`__gt__()`](https://docs.python.org/3/reference/datamodel.html#object.__gt__) method.<br>For sorting examples and a brief sorting tutorial, see [Sorting Techniques](https://docs.python.org/3/howto/sorting.html#sortinghowto). |
|
63 | [`in`](https://docs.python.org/reference/expressions.html#membership-test-operations) tests for the existence of a key in a [`dict`](https://docs.python.org/library/stdtypes.html#dict):<br><br>```python<br>d = {"key1": 10, "key2": 23}<br><br>if "key1" in d:<br> print("this will execute")<br><br>if "nonexistent key" in d:<br> print("this will not")<br><br>```<br><br>---<br><br>Use [`dict.get()`](https://docs.python.org/library/stdtypes.html#dict.get) to provide a default value when the key does not exist:<br><br>```python<br>d = {}<br><br>for i in range(100):<br> key = i % 10<br> d[key] = d.get(key, 0) + 1<br><br>```<br><br>---<br><br>To provide a default value for *every* key, either use [`dict.setdefault()`](https://docs.python.org/library/stdtypes.html#dict.setdefault) on each assignment:<br><br>```python<br>d = {}<br><br>for i in range(100):<br> d[i % 10] = d.setdefault(i % 10, 0) + 1<br><br>```<br><br>...or better, use [`defaultdict`](https://docs.python.org/library/collections.html#collections.defaultdict) from the [`collections`](https://docs.python.org/library/collections.html) module:<br><br>```python<br>from collections import defaultdict<br><br>d = defaultdict(int)<br><br>for i in range(100):<br> d[i % 10] += 1<br>``` |
|
64 | ```python<br>d = {}<br><br>for i in range(100):<br> key = i % 10<br> d[key] = d.get(key, 0) + 1<br><br>``` |
|
65 | **get**(*key*, *default=None*)<br><br>Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError). |
|
66 | Use [`random.choice()`](https://docs.python.org/library/random.html#random.choice):<br><br>```python<br>import random<br><br>foo = ['a', 'b', 'c', 'd', 'e']<br>print(random.choice(foo))<br><br>```<br><br>For [cryptographically secure](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) random choices (e.g., for generating a passphrase from a wordlist), use [`secrets.choice()`](https://docs.python.org/library/secrets.html#secrets.choice):<br><br>```python<br>import secrets<br><br>foo = ['battery', 'correct', 'horse', 'staple']<br>print(secrets.choice(foo))<br><br>```<br><br>`secrets` is new in Python 3.6. On older versions of Python you can use the [`random.SystemRandom`](https://docs.python.org/library/random.html#random.SystemRandom) class:<br><br>```python<br>import random<br><br>secure_random = random.SystemRandom()<br>print(secure_random.choice(foo))<br>``` |
|
67 | ```python<br>import random<br><br>foo = ['a', 'b', 'c', 'd', 'e']<br>print(random.choice(foo))<br><br>``` |
|
68 | random.**choice**(*seq*)<br><br>Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError). |
|
69 | The best way to do this in Pandas is to use [`drop`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html):<br><br>```python<br>df = df.drop('column_name', axis=1)<br><br>```<br><br>where `1` is the *axis* number (`0` for rows and `1` for columns.)<br><br>Or, the `drop()` method accepts `index`/`columns` keywords as an alternative to specifying the axis. So we can now just do:<br><br>```python<br>df = df.drop(columns=['column_nameA', 'column_nameB'])<br><br>```<br><br>- *This was [introduced in v0.21.0](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.21.0.html#method-drop-now-also-accepts-index-columns-keywords) (October 27, 2017)*<br><br>To delete the column without having to reassign `df` you can do:<br><br>```python<br>df.drop('column_name', axis=1, inplace=True)<br><br>```<br><br>Finally, to drop by column *number* instead of by column *label*, try this to delete, e.g. the 1st, 2nd and 4th columns:<br><br>```python<br>df = df.drop(df.columns[[0, 1, 3]], axis=1) # df.columns is zero-based pd.Index<br><br>```<br><br>Also working with "text" syntax for the columns:<br><br>```python<br>df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)<br>``` |
|
70 | ```python<br>df = df.drop('column_name', axis=1)<br><br>``` |
|
71 | # pandas.DataFrame.drop<br><br>**DataFrame.drop(*labels=None*, ***, *axis=0*, *index=None*, *columns=None*, *level=None*, *inplace=False*, *errors='raise'*)[[source]](https://github.com/pandas-dev/pandas/blob/v2.2.2/pandas/core/frame.py#L5433-L5589)**Drop specified labels from rows or columns.<br>Remove rows or columns by specifying label names and corresponding axis, or by directly specifying index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. See the [user guide](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-shown-levels) for more information about the now unused levels. |
|
72 | Use [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:<br><br>```python<br>>>> from collections import Counter<br>>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']<br>>>> Counter(z)<br>Counter({'blue': 3, 'red': 2, 'yellow': 1})<br>``` |
|
73 | <br>```python<br>>>> from collections import Counter<br>>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']<br>>>> Counter(z)<br>Counter({'blue': 3, 'red': 2, 'yellow': 1})<br>``` |
|
74 | *class* collections.**Counter**([*iterable-or-mapping*])<br><br>A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) subclass for counting [hashable](https://docs.python.org/3/glossary.html#term-hashable) objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) class is similar to bags or multisets in other languages.<br>Elements are counted from an *iterable* or initialized from another *mapping* (or counter):~~>>>~~<br><br>`c = Counter() *# a new, empty counter*c = Counter('gallahad') *# a new counter from an iterable*c = Counter({'red': 4, 'blue': 2}) *# a new counter from a mapping*c = Counter(cats=4, dogs=8) *# a new counter from keyword args*`<br>Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError):~~>>>~~<br><br>`c = Counter(['eggs', 'ham'])<br>c['bacon'] *# count of a missing element is zero*`<br>Setting a count to zero does not remove an element from a counter. Use `del` to remove it entirely:~~>>>~~<br><br>`c['sausage'] = 0 *# counter entry with a zero count***del** c['sausage'] *# del actually removes the entry*`<br>*Added in version 3.1.*<br>*Changed in version 3.7:* As a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) subclass, [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) inherited the capability to remember insertion order. Math operations on *Counter* objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand. |
|
75 | Set the mode in [`open()`](https://docs.python.org/3/library/functions.html#open) to `"a"` (append) instead of `"w"` (write):<br><br>```python<br>with open("test.txt", "a") as myfile:<br> myfile.write("appended text")<br><br>```<br><br>The [documentation](https://docs.python.org/3/library/functions.html#open) lists all the available modes. |
|
76 | ```python<br>with open("test.txt", "a") as myfile:<br> myfile.write("appended text")<br><br>``` |
|
77 | **open**(*file*, *mode='r'*, *buffering=-1*, *encoding=None*, *errors=None*, *newline=None*, *closefd=True*, *opener=None*)[¶](https://docs.python.org/3/library/functions.html#open)<br><br>Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.<br>*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)<br>*mode* is an optional string that specifies the mode in which the file is opened. It defaults to `'r'` which means open for reading in text mode. Other common values are `'w'` for writing (truncating the file if it already exists), `'x'` for exclusive creation, and `'a'` for appending (which on *some* Unix systems, means that *all* writes append to the end of the file regardless of the current seek position). In text mode, if *encoding* is not specified the encoding used is platform-dependent: [`locale.getencoding()`](https://docs.python.org/3/library/locale.html#locale.getencoding) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave *encoding* unspecified.) |
|
78 | Try the method `rstrip()` (see doc [Python 2](http://docs.python.org/2/library/stdtypes.html#str.rstrip) and [Python 3](https://docs.python.org/3/library/stdtypes.html#str.rstrip))<br><br>```python<br>>>> 'test string\n'.rstrip()<br>'test string'<br><br>```<br><br>Python's `rstrip()` method strips *all* kinds of trailing whitespace by default, not just one newline as Perl does with [`chomp`](http://perldoc.perl.org/functions/chomp.html).<br><br>```python<br>>>> 'test string \n \r\n\n\r \n\n'.rstrip()<br>'test string'<br><br>```<br><br>To strip only newlines:<br><br>```python<br>>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')<br>'test string \n \r\n\n\r '<br><br>```<br><br>In addition to `rstrip()`, there are also the methods `strip()` and `lstrip()`. Here is an example with the three of them:<br><br>```python<br>>>> s = " \n\r\n \n abc def \n\r\n \n "<br>>>> s.strip()<br>'abc def'<br>>>> s.lstrip()<br>'abc def \n\r\n \n '<br>>>> s.rstrip()<br>' \n\r\n \n abc def'<br>``` |
|
79 | ```python<br>>>> 'test string \n \r\n\n\r \n\n'.rstrip()<br>'test string'<br><br>``` |
|
80 | bytes.strip([chars])<br>bytearray.strip([chars])<br>Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:<br>>>><br>>>> b' spacious '.strip()<br>b'spacious'<br>>>> b'www.example.com'.strip(b'cmowz.')<br>b'example'<br>The binary sequence of byte values to remove may be any bytes-like object.<br>Note<br> <br>The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made.<br>The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects. |
|
81 | For non-negative (unsigned) integers only, use [`isdigit()`](https://docs.python.org/3/library/stdtypes.html#str.isdigit):<br><br>```python<br>>>> a = "03523"<br>>>> a.isdigit()<br>True<br>>>> b = "963spam"<br>>>> b.isdigit()<br>False<br><br>```<br><br>---<br><br>Documentation for `isdigit()`: [Python2](https://docs.python.org/2/library/stdtypes.html#str.isdigit), [Python3](https://docs.python.org/3/library/stdtypes.html#str.isdigit)<br><br>For Python 2 Unicode strings: [`isnumeric()`](https://docs.python.org/2/library/stdtypes.html#unicode.isnumeric). |
|
82 | ```python<br>>>> a = "03523"<br>>>> a.isdigit()<br>True<br>>>> b = "963spam"<br>>>> b.isdigit()<br>False<br><br>``` |
|
83 | str.**isdigit**()<br><br>Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal. |
|
84 | Use the `indent=` parameter of [`json.dump()`](https://docs.python.org/3/library/json.html#json.dump) or [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) to specify how many spaces to indent by:<br><br>```python<br>>>> import json<br>>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'<br>>>> parsed = json.loads(your_json)<br>>>> print(json.dumps(parsed, indent=4))<br>[<br> "foo",<br> {<br> "bar": [<br> "baz",<br> null,<br> 1.0,<br> 2<br> ]<br> }<br>]<br><br>```<br><br>To parse a file, use [`json.load()`](https://docs.python.org/3/library/json.html#json.load):<br><br>```python<br>with open('filename.txt', 'r') as handle:<br> parsed = json.load(handle)<br>``` |
|
85 | ```python<br>>>> import json<br>>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'<br>>>> parsed = json.loads(your_json)<br>>>> print(json.dumps(parsed, indent=4))<br>[<br> "foo",<br> {<br> "bar": [<br> "baz",<br> null,<br> 1.0,<br> 2<br> ]<br> }<br>]<br><br>``` |
|
86 | son.**dump**(*obj*, *fp*, ***, *skipkeys=False*, *ensure_ascii=True*, *check_circular=True*, *allow_nan=True*, *cls=None*, *indent=None*, *separators=None*, *default=None*, *sort_keys=False*, ***kw*)<br><br>Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).<br>If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), [`float`](https://docs.python.org/3/library/functions.html#float), [`bool`](https://docs.python.org/3/library/functions.html#bool), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError).<br>The [`json`](https://docs.python.org/3/library/json.html#module-json) module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str) objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str) input.<br>If *ensure_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure_ascii* is false, these characters will be output as-is.<br>If *check_circular* is false (default: `True`), then the circular reference check for container types will be skipped and a circular reference will result in a [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError) (or worse).<br>If *allow_nan* is false (default: `True`), then it will be a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) to serialize out of range [`float`](https://docs.python.org/3/library/functions.html#float) values (`nan`, `inf`, `-inf`) in strict compliance of the JSON specification. If *allow_nan* is true, their JavaScript equivalents (`NaN`, `Infinity`, `-Infinity`) will be used.<br>If *indent* is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or `""` will only insert newlines. `None` (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If *indent* is a string (such as `"\t"`), that string is used to indent each level.<br>*Changed in version 3.2:* Allow strings for *indent* in addition to integers.<br>If specified, *separators* should be an `(item_separator, key_separator)` tuple. The default is `(', ', ': ')` if *indent* is `None` and `(',', ': ')` otherwise. To get the most compact JSON representation, you should specify `(',', ':')` to eliminate whitespace.<br>*Changed in version 3.4:* Use `(',', ': ')` as default if *indent* is not `None`.<br>If specified, *default* should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError). If not specified, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised.<br>If *sort_keys* is true (default: `False`), then the output of dictionaries will be sorted by key.<br>To use a custom [`JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder) subclass (e.g. one that overrides the [`default()`](https://docs.python.org/3/library/json.html#json.JSONEncoder.default) method to serialize additional types), specify it with the *cls* kwarg; otherwise [`JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder) is used.<br>*Changed in version 3.6:* All optional parameters are now [keyword-only](https://docs.python.org/3/glossary.html#keyword-only-parameter).<br>**Note** <br>Unlike [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) and [`marshal`](https://docs.python.org/3/library/marshal.html#module-marshal), JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to [`dump()`](https://docs.python.org/3/library/json.html#json.dump) using the same *fp* will result in an invalid JSON file. |
|
87 | Use [`isinstance`](https://docs.python.org/library/functions.html#isinstance) to check if `o` is an instance of `str` or any subclass of `str`:<br><br>```python<br>if isinstance(o, str):<br><br>```<br><br>To check if the type of `o` is exactly `str`, *excluding subclasses of `str`*:<br><br>```python<br>if type(o) is str:<br><br>```<br><br>See [Built-in Functions](http://docs.python.org/library/functions.html) in the Python Library Reference for relevant information.<br><br>---<br><br>### Checking for strings in Python 2<br><br>For Python 2, this is a better way to check if `o` is a string:<br><br>```python<br>if isinstance(o, basestring):<br><br>```<br><br>because this will also catch Unicode strings. [`unicode`](https://docs.python.org/2/library/functions.html#unicode) is not a subclass of `str`; both `str` and `unicode` are subclasses of [`basestring`](https://docs.python.org/2/library/functions.html#basestring). In Python 3, `basestring` no longer exists since there's [a strict separation](https://docs.python.org/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit) of strings ([`str`](https://docs.python.org/3/library/functions.html#func-str)) and binary data ([`bytes`](https://docs.python.org/3/library/functions.html#func-bytes)).<br><br>Alternatively, `isinstance` accepts a tuple of classes. This will return `True` if `o` is an instance of any subclass of any of `(str, unicode)`:<br><br>```python<br>if isinstance(o, (str, unicode)):<br>``` |
|
88 | ```python<br>if isinstance(o, str):<br><br>``` |
|
89 | **isinstance**(*object*, *classinfo*)<br><br>Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) may not be raised for an invalid type if an earlier check succeeds.<br>*Changed in version 3.10: classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union). |
|
90 | When using [`matplotlib.pyplot.savefig`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html), the file format can be specified by the extension:<br><br>```python<br>from matplotlib import pyplot as plt<br><br>plt.savefig('foo.png')<br>plt.savefig('foo.pdf')<br><br>```<br><br>That gives a rasterized or vectorized output respectively. In addition, there is sometimes undesirable whitespace around the image, which can be removed with:<br><br>```python<br>plt.savefig('foo.png', bbox_inches='tight')<br><br>```<br><br>Note that if showing the plot, `plt.show()` should follow `plt.savefig()`; otherwise, the file image will be blank. |
|
91 | ```python<br>from matplotlib import pyplot as plt<br><br>plt.savefig('foo.png')<br>plt.savefig('foo.pdf')<br><br>``` |
|
92 | # matplotlib.pyplot.savefig<br><br>**matplotlib.pyplot.savefig(**args*, ***kwargs*)[[source]](https://github.com/matplotlib/matplotlib/blob/v3.9.1/lib/matplotlib/pyplot.py#L1223-L1230)**Save the current figure as an image or vector graphic to a file.<br>Call signature:<br><br>`savefig(fname, *, transparent=None, dpi='figure', format=None,<br> metadata=None, bbox_inches=None, pad_inches=0.1,<br> facecolor='auto', edgecolor='auto', backend=None,<br> **kwargs<br> )`<br><br>The available output formats depend on the backend being used.**Parameters:fnamestr or path-like or binary file-like**A path, or a Python file-like object, or possibly some backend-dependent object such as [**`matplotlib.backends.backend_pdf.PdfPages`**](https://matplotlib.org/stable/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages).<br>If *format* is set, it determines the output format, and the file is saved as *fname*. Note that *fname* is used verbatim, and there is no attempt to make the extension, if any, of *fname* match *format*, and no extension is appended.<br>If *format* is not set, then the format is inferred from the extension of *fname*, if there is one. If *format* is not set and *fname* has no extension, then the file is saved with [`rcParams["savefig.format"]`](https://matplotlib.org/stable/users/explain/customizing.html?highlight=savefig.format#matplotlibrc-sample) (default: `'png'`) and the appropriate extension is appended to *fname*. |
|
93 | ### Python 3.4+<br><br>Use [`pathlib.Path.stem`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem)<br><br>```python<br>>>> from pathlib import Path<br>>>> Path("/path/to/file.txt").stem<br>'file'<br>>>> Path("/path/to/file.tar.gz").stem<br>'file.tar'<br><br>```<br><br>### Python < 3.4<br><br>Use [`os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext) in combination with [`os.path.basename`](https://docs.python.org/3/library/os.path.html#os.path.basename):<br><br>```python<br>>>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0]<br>'file'<br>>>> os.path.splitext(os.path.basename("/path/to/file.tar.gz"))[0]<br>'file.tar'<br>``` |
|
94 | <br>```python<br>>>> from pathlib import Path<br>>>> Path("/path/to/file.txt").stem<br>'file'<br>>>> Path("/path/to/file.tar.gz").stem<br>'file.tar'<br><br>``` |
|
95 | PurePath.**stem**<br><br>The final path component, without its suffix:>>><br><br>**`>>>** PurePosixPath('my/library.tar.gz').stem<br>'library.tar'<br>**>>>** PurePosixPath('my/library.tar').stem<br>'library'<br>**>>>** PurePosixPath('my/library').stem<br>'library'` |
|
96 | Use [**`os.path.isdir`**](http://docs.python.org/dev/library/os.path.html#os.path.isdir) for directories only:<br><br>```python<br>>>> import os<br>>>> os.path.isdir('new_folder')<br>True<br><br>```<br><br>Use [**`os.path.exists`**](http://docs.python.org/dev/library/os.path.html#os.path.exists) for both files and directories:<br><br>```python<br>>>> import os<br>>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))<br>False<br><br>```<br><br>Alternatively, you can use [**`pathlib`**](https://docs.python.org/dev/library/pathlib.html):<br><br>```python<br> >>> from pathlib import Path<br> >>> Path('new_folder').is_dir()<br> True<br> >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()<br> False<br>``` |
|
97 | <br>```python<br>>>> import os<br>>>> os.path.isdir('new_folder')<br>True<br><br>``` |
|
98 | os.path.**isdir**(*path*)<br><br>Return `True` if *path* is an [`existing`](https://docs.python.org/dev/library/os.path.html#os.path.exists) directory. This follows symbolic links, so both [`islink()`](https://docs.python.org/dev/library/os.path.html#os.path.islink) and [`isdir()`](https://docs.python.org/dev/library/os.path.html#os.path.isdir) can be true for the same path.<br>*Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/dev/glossary.html#term-path-like-object). |
|
99 | [`os.rename()`](http://docs.python.org/library/os.html#os.rename), [`os.replace()`](https://docs.python.org/library/os.html#os.replace), or [`shutil.move()`](http://docs.python.org/library/shutil.html#shutil.move)<br><br>All employ the same syntax:<br><br>```python<br>import os<br>import shutil<br><br>os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")<br>os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")<br>shutil.move("path/to/current/file.foo", "path/to/new/destination/for/file.foo")<br><br>```<br><br>- The filename (`"file.foo"`) must be included in both the source and destination arguments. If it differs between the two, the file will be renamed as well as moved.<br>- The directory within which the new file is being created must already exist.<br>- On Windows, a file with that name must not exist or an exception will be raised, but `os.replace()` will silently replace a file even in that occurrence.<br>- `shutil.move` simply calls `os.rename` in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file. |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 54