Dataset Viewer
Auto-converted to Parquet Duplicate
_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 prese...
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 ...
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 ...
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....
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...
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 `@cla...
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>d...
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...
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> ...
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<...
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, althou...
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 encod...
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/co...
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...
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 O...
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 Pyt...
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...
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 o...
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.copyf...
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 ...
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...
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....
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, su...
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 pl...
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 f...
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...
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 f...
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* const...
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 un...
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....
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 "colo...
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>```...
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#mut...
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...
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...
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': 'newNam...
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 / di...
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 th...
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.itemgette...
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* (...
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" ...
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)...
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...
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...
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>Cou...
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...
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 ...
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 ...
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 traili...
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...
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.py...
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...
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>>...
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> }...
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.pytho...
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 st...
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...
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 rasterize...
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='f...
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 [`o...
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 dire...
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/o...
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/t...
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
104