# Python Tutorials

### [How to Copy a File in Python?](https://itsmycode.com/how-to-copy-a-file-in-python/)

We can copy a file in Python using **shutil, os, and subprocess modules**. Let’s take a look at each of these modules and the functions it has with examples.

### Modules to copy a file in Python  <a href="#modules-to-copy-a-file-in-python" id="modules-to-copy-a-file-in-python"></a>

* **shutil module**
* **os module**
* **subprocess module**

### [How to Create a Directory in Python?](https://itsmycode.com/how-to-create-a-directory-in-python/)

The **`os`** module is a built-in utility available in both Python 2 and 3 versions, and it provides functions to interact easily with the operating system. The os and **`os.path`** modules provide various functions to interact with the file system.

Let’s take a look at various ways through which you can **create a directory in Python using the os module.**<br>

### [Convert String to Float in Python](https://itsmycode.com/convert-string-to-float-in-python/)

Usually, in Python, the user input that we get will be a string when you read the data from the terminal, excel, CSV, or from a web form. We need to convert the string explicitly into the floating-point value before performing any arithmetic operations. Otherwise, Python will throw valueerror.

### [Python Multiline comment](https://itsmycode.com/python-comment-block/)

Comments are a piece of text in a computer program that provides more information on the source code written. Like every other programming language, Python has three different types of comments: single-line comments, multiline comments, and documentation string to comment out block of code.

### [TypeError: ‘list’ object is not callable](https://itsmycode.com/typeerror-list-object-is-not-callable/)

The most common scenario where Python throws **TypeError: ‘list’ object is not callable** is when you have assigned a variable name as “list” or if you are trying to index the elements of the list using parenthesis instead of square brackets.

### [Python can’t Multiply Sequence by non-int of type ‘float’](https://itsmycode.com/solved-python-cant-multiply-sequence-by-non-int-of-type-float/)

The TypeError: can’t multiply sequence by non-int of type ‘float’ occurs if we use the multiply operator between a string and float value.&#x20;

### [Python TypeError: ‘int’ object is not subscriptable](https://itsmycode.com/python-typeerror-int-object-is-not-subscriptable/)

In Python, we use Integers to store the whole numbers, and it is not **a subscriptable object.** If you treat an integer like a subscriptable object, the Python interpreter will raise **TypeError: ‘int’ object is not subscriptable**.

### [Python String swapcase()](https://itsmycode.com/python-string-swapcase/)

Python string swapcase() method is a built-in function that converts all uppercase characters into lowercase and all lowercase characters into uppercase characters of a given string and returns a new string.

### [TypeError: list indices must be integers or slices, not str](https://itsmycode.com/typeerror-list-indices-must-be-integers-or-slices-not-str/)

If you are accessing the elements of a list in Python, you need to access it using its index position or slicing. However, if you try to access a list value using a string Python will raise **TypeError: list indices must be integers or slices, not str** exception.

### [ **TypeError: can’t multiply sequence by non-int of type ‘str’**](https://itsmycode.com/solved-python-cant-multiply-sequence-by-non-int-of-type-str/)

The TypeError: can’t multiply sequence by non-int of type ‘str’ occurs if we multiply a string by another string without converting into an integer or floating-point.

### [No handles with labels found to put in legend](https://itsmycode.com/no-handles-with-labels-found-to-put-in-legend/)

In Python matplotlib No handles with labels found to put in legend occur if you have not defined the label parameters whenever you plot the figure and try to call the **`plt.legend()`** method.

### [ValueError: If using all scalar values, you must pass an index](https://itsmycode.com/valueerror-if-using-all-scalar-values-you-must-pass-an-index/)

If you pass all scalar values while creating pandas Dataframe in Python, you will encounter “**ValueError: If using all scalar values, you must pass an index**“

### [NameError: name ‘pd’ is not defined](https://itsmycode.com/solved-nameerror-name-pd-is-not-defined/)

In Python, **NameError: name ‘pd’ is not defined** occurs when you import the pandas library but fail to provide the alias as pd while importing it.

### [NameError: name ‘np’ is not defined](https://itsmycode.com/solved-nameerror-name-np-is-not-defined/)

In Python, NameError: name ‘np’ is not defined occurs when you import the NumPy library but fail to provide the alias as np while importing it.<br>

### [How to Fix: KeyError in Pandas?](https://itsmycode.com/how-to-fix-keyerror-in-pandas/)

The KeyError in Padas occurs when you try to access the columns in pandas DataFrame, which does not exist, or you misspell them.

### [How to Fix in Python ValueError: Trailing data?](https://itsmycode.com/how-to-fix-in-python-valueerror-trailing-data/)

In Python ValueError: Trailing data occurs when you try to load the JSON data or file into pandas DataFrame, and the data is written in lines separated with newline characters<br>

### [\[Solved\] Pandas TypeError: no numeric data to plot](https://itsmycode.com/solved-pandas-typeerror-no-numeric-data-to-plot/)

In Pandas, we can only plot values with the numeric data type. If you try to plot with any other Data Type other than numeric data, Python will raise TypeError: no numeric data to plot\\

### [AttributeError: ‘numpy.ndarray’ object has no attribute ‘index’](https://itsmycode.com/attributeerror-numpy-ndarray-object-has-no-attribute-index/)

The **AttributeError: ‘numpy.ndarray’ object has no attribute ‘index’** occurs when you attempt to use the **`index()`** method on a NumPy array that does not have any index attribute to use.

### [How to rename columns in Pandas DataFrame](https://itsmycode.com/how-to-rename-columns-in-pandas-dataframe/)

Pandas is a useful library in data analysis, and Pandas DataFrame is Two-dimensional, size-mutable, potentially heterogeneous tabular data. In this tutorial, let’s see how to rename columns in Pandas DataFrame.

### [TypeError: ‘numpy.float64’ object cannot be interpreted as an integer](https://itsmycode.com/typeerror-numpy-float64-object-cannot-be-interpreted-as-an-integer/)

The **TypeError: ‘numpy.float64’ object cannot be interpreted as an integer** occurs if you pass a float value to a function like **`range()`** which accepts only integer.

### [Pandas : How to Find Unique Values in a Column](https://itsmycode.com/pandas-how-to-find-unique-values-in-a-column/)

We can find unique values of a column in Pandas DataFrame using the unique() function. The unique() method filters out only unique values from a column.\ <br>

### [Python String rstrip()](https://itsmycode.com/python-string-rstrip/)

The Python String rstrip() method is a built-in function that strips trailing characters based on the arguments passed to the function and returns the copy of a string.<br>

### [Python String lstrip()](https://itsmycode.com/python-string-lstrip/)

The Python String lstrip() method is a built-in function that strips leading characters based on the arguments passed to the function and returns the copy of a string.

### [Python String strip()](https://itsmycode.com/python-string-strip/)

The Python String strip() method is a built-in function that strips both leading and trailing characters based on the arguments passed to the function and returns the copy of a string

### [Python String split()](https://itsmycode.com/python-string-split/)

The Python String split() method is a built-in function that splits the string based on the specified separator and returns a list of strings.<br>

### [Python String rsplit()](https://itsmycode.com/python-string-rsplit/)

The Python String rsplit() method is a built-in function that splits the string at the specified separator from the right side and returns a list of strings.

### [Python String title()](https://itsmycode.com/python-string-title/)

The Python String title() method is a built-in function that returns a string where the first character of each word is uppercase.

### [Python String zfill()](https://itsmycode.com/python-string-zfill/)

The Python String zfill() method is a built-in function that adds zeros (0) at the beginning of the string until it reaches the specified length and returns the copy of a string.

### [Python String isdecimal()](https://itsmycode.com/python-string-isdecimal/)

The Python String isdecimal() method is a built-in function that returns true if all the characters in a string are decimal.<br>

### [Python String isidentifier()](https://itsmycode.com/python-string-isidentifier/)

The Python String isidentifier() method is a built-in function that returns true if the string is a valid identifier.

### [Python String rfind()](https://itsmycode.com/python-string-rfind/)

The Python String rfind() method is a built-in function that returns the substring’s highest index (last occurrence) in a given string. If not found, it returns -1

### [Python String isprintable()](https://itsmycode.com/python-string-isprintable/)

The Python String isprintable() method is a built-in function that returns true if all the characters in a string are printable or if the string is empty.<br>

### [Python String find()](https://itsmycode.com/python-string-find/)

The Python String find() method is a built-in function that returns the index of the first occurrence of a substring in a given string. If not found, it returns -1

### [Python String rindex()](https://itsmycode.com/python-string-rindex/)

The Python String rindex() method is a built-in function that returns the substring’s highest index (last occurrence) in a given string. If not found, it raises ValueError: substring not found

### [Python String index()](https://itsmycode.com/python-string-index/)

The Python String index() method is a built-in function that returns the substring’s lowest index (first occurrence) in a given string. If not found, it raises ValueError: substring not found<br>

### [How to Import CSV Files into R?](https://itsmycode.com/how-to-import-csv-files-into-r/)

There are 3 popular methods available to import CSV files into R.&#x20;

* **Using read.csv() method**
* **Using read\_csv() method**
* **Using fread() method**

### &#x20;[Adding new column to existing DataFrame in Pandas](https://itsmycode.com/adding-new-column-to-existing-dataframe-in-pandas/)

In this article, we will look at different ways to adding new column to existing DataFrame in Pandas.&#x20;

Let us create a simple DataFrame that we will use as a reference throughout this article to demonstrate adding new columns into Pandas DataFrame.

### [Python Print Variable](https://itsmycode.com/python-print-variable/)

Python is one of the most versatile programming languages, and we can use the print statement in several ways to print a variable in Python.

In this article, let us look at different approaches available in [Python to print](https://itsmycode.com/how-to-check-and-print-python-version/) a variable with examples.

### [Calculate Euclidean Distance in Python](https://itsmycode.com/calculate-euclidean-distance-in-python/)

In mathematics, the Euclidean Distance refers to the distance between two points in the plane or 3-dimensional space. In short, we can say that it is the shortest distance between 2 points irrespective of dimensions.

### [ PermissionError: \[Errno 13\] Permission denied](https://itsmycode.com/python-permissionerror-errno-13-permission-denied/)

If we provide a folder path instead of a file path while reading file or if Python does not have the required permission to perform file operations(open, read, write) etc

### [How to Create a Pie Chart in Seaborn](https://itsmycode.com/how-to-create-a-pie-chart-in-seaborn/)

We do not have any built-in function to create Pie chart in seaborn, but with the help of Matplotlib, we can create a pie chart and leverage seaborn for color pallets.

### [How to Add a Title to Seaborn Plots](https://itsmycode.com/how-to-add-a-title-to-seaborn-plots/)

There are four different methods to add a title to seaborn plots. Let us explore each of these methods in detail with examples.

### [How to Fix: module ‘pandas’ has no attribute ‘dataframe’](https://itsmycode.com/how-to-fix-module-pandas-has-no-attribute-dataframe/)

We get **AttributeError: module ‘pandas’ has no attribute ‘dataframe’** when the Pandas module is unable to resolve and initialize the DataFrame class. The AttributeError usually occurs if the class is not defined in the module or if it has a different name.

### &#x20;[\[Solved\] Uncaught SyntaxError: cannot use import statement outside a module](https://itsmycode.com/solved-uncaught-syntaxerror-cannot-use-import-statement-outside-a-module/)

The **Uncaught syntaxerror: cannot use import statement outside a module** occurs if you have forgotten to add **`type="module"`** attribute while loading the script or if you are loading the src file instead of bundled file from the dist folder.

### [TypeError: can only concatenate str (not “int”) to str](https://itsmycode.com/typeerror-can-only-concatenate-str-not-int-to-str/)

In Python, we can concatenate values if they are of the same type. Let’s say if you concatenate a string and an integer you will get **TypeError: can only concatenate str (not “int”) to str**

### [TypeError: only size-1 arrays can be converted to python scalars](https://itsmycode.com/typeerror-only-size-1-arrays-can-be-converted-to-python-scalars/)

We get this error generally while working with NumPy and Matplotlib. If you have a function that accepts a single value, but if you pass an array instead, you will encounter **TypeError: only size-1 arrays can be converted to python scalars.**

### [TypeError: ‘float’ object is not callable](https://itsmycode.com/typeerror-float-object-is-not-callable/)

The **TypeError: ‘float’ object is not callable** error occurs if you call floating-point value as a function or if an arithmetic operator is missed while performing the calculations or the reserved keywords are declared as variables and used as functions,&#x20;

### [TypeError: ‘builtin\_function\_or\_method’ object is not subscriptable](https://itsmycode.com/builtin-function-or-method-object-is-not-subscriptable/)

In Python, Built-in functions are not subscriptable, if we use the built-in functions as an array to perform operations such as indexing, you will encounter **TypeError: ‘builtin\_function\_or\_method’ object is not subscriptable**.

### [ImportError: No module named matplotlib.pyplot](https://itsmycode.com/solved-importerror-no-module-named-matplotlib-pyplot/)

The **ImportError: No module named matplotlib.pyplot** occurs if you have not installed the Matplotlib library in Python and trying to run the script which has matplotlib related code. Another issue might be that you are not importing the `matplotlib.pyplot` properly in your Python code.

### [TypeError: method() takes 1 positional argument but 2 were given](https://itsmycode.com/method-takes-1-positional-argument-but-2-were-given/)

If you define a method inside a class, you should add `self` as the first argument. If you forget the self argument, then Python will raise **TypeError: method() takes 1 positional argument but 2 were given**

### [Support for password authentication was removed. Please use a personal access token instead](https://itsmycode.com/support-for-password-authentication-was-removed-github/)

If you perform Git operations and try to authenticate using the account username and password, you will get an error **remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead**.

### [\[Solved\] Error in plot.new() : figure margins too large](https://itsmycode.com/solved-error-in-plot-new-figure-margins-too-large/)

The **error in plot.new() : figure margins too large** occur if the plot panel in the RStudio is too small for the margins you are trying to create.

### [\[Solved\] ImportError: cannot import name ‘json’ from itsdangerous](https://itsmycode.com/importerror-cannot-import-name-json-from-itsdangerous/)

If you are deploying and running the flask application with 1.1.2 version by using the Docker containers, you will get **ImportError: cannot import name ‘json’ from itsdangerous**

The Flask version 1.1.2 has a dependency on markupsafe and itsdangerous packages. The issue is with MarkupSafe:2.1.0 where they have removed soft\_unicode.

### [\[Solved\] error:0308010C:digital envelope routines::unsupported](https://itsmycode.com/error-digital-envelope-routines-unsupported/)

The error:0308010C:digital envelope routines::unsupported is mainly observed while creating the react application using the Node.JS version 17 or above and using the webpack\@4 version.

### [\[Solved\] Error: command errored out with exit status 1](https://itsmycode.com/error-command-errored-out-with-exit-status-1/)

If you are installing **auto-py-to-exe** package on Python 3.8 or below, you will get an error stating **ERROR: Command errored out with exit status 1**: python setup.py egg\_info Check the logs for full command output.

### [\[Solved\] Importerror: libgl.so.1: cannot open shared object file: no such file or directory](https://itsmycode.com/importerror-libgl-so-1-cannot-open-shared-object-file-no-such-file-or-directory/)

If you are using **`cv2`** or **`opencv-python`** and then building the application through docker you will get an **importerror: libgl.so.1: cannot open shared object file: no such file or directory.**

### [\[Solved\] Crbug/1173575, non-JS module files deprecated.](https://itsmycode.com/crbug-1173575-non-js-module-files-deprecated/)

The error **Crbug/1173575, non-JS module files deprecated** occurs mainly if you are trying to debug the application in VSCode and Chrome browser. There are various reasons why you get the error.

### [\[Solved\] remote: Bitbucket Cloud recently stopped supporting account passwords for Git authentication](https://itsmycode.com/solved-remote-bitbucket-cloud-recently-stopped-supporting-account-passwords-for-git-authentication/)

Starting from March 1, 2022, Bitbucket Cloud users will no longer be able to use their account passwords when using Basic authentication for Git over HTTPS and the Bitbucket Cloud REST API. If you try to use an account password for Git operations, you will get an error **remote: Bitbucket Cloud recently stopped supporting account passwords for Git authentication**.

### [SyntaxError: Positional argument follows keyword argument](https://itsmycode.com/positional-argument-follows-keyword-argument/)

If you provide the keyword argument first followed by a positional argument, the Python interpreter will raise SyntaxError: positional argument follows keyword argument.

### [AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’](https://itsmycode.com/numpy-ndarray-object-has-no-attribute-append/)'

If you use the regular Python list append() method to add an element to the end of NumPy array, you will encounter AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’.

### [ RuntimeWarning: invalid value encountered in true\_divide](https://itsmycode.com/invalid-value-encountered-in-true-divide/)

Suppose you attempt to divide the NumPy arrays elements using the divide() method with invalid values such as 0/0, NaN Infinity, zero, etc. you will encounter a RuntimeWarning: invalid value encountered in true\_divide.

### [ValueError: cannot convert float NaN to integer](https://itsmycode.com/cannot-convert-float-nan-to-integer/)

The ValueError: cannot convert float NaN to integer occurs when we attempt to convert the pandas DataFrame column from float to an integer where the column contains NaN value.

### [AttributeError: ‘str’ object has no attribute ‘decode’](https://itsmycode.com/attributeerror-str-object-has-no-attribute-decode/)

In Python 3, all the strings are in Unicode format by default. If you try to decode the Unicode string in Python 3, you will encounter an **AttributeError: ‘str’ object has no attribute ‘decode’**.

### [Convert Letters to Numbers in Python](https://itsmycode.com/convert-letters-to-numbers-in-python/)

Using the ord() method, we can convert letters to numbers in Python. The ord() method returns an integer representing the Unicode character.

### [Python List count()](https://itsmycode.com/python-list-count/)

Python List count() is a built-in function that returns the number of times the specified element occurs in the list.

### [Python List clear()](https://itsmycode.com/python-list-clear/)

Python List clear() is a built-in function that removes all the items and makes a list empty.

### [Python List remove()](https://itsmycode.com/python-list-remove/)

Python List remove() is a built-in function that removes the first occurrence element from the list.

### [Python List insert()](https://itsmycode.com/python-list-insert/)

Python List insert() is a built-in function that inserts the given element at a specified index.

### [Python List extend()](https://itsmycode.com/python-list-extend/)

The **extend() method** in Python adds the iterable elements (list, tuple, string etc.) to the end of the list. The length of the list is increased by the number of elements present in the iterable.

### [Python List append()](https://itsmycode.com/python-list-append/)

The append() method in Python adds an element to the end of the list. After appending the new element, the size of the list increases by one.

### [Python List index()](https://itsmycode.com/python-list-index/)

The **Python list index()** is a built-in function that searches for a given element from the start of the list and returns the lowest index where the element appears in the list.

### [\[Solved\] DeprecationWarning: executable\_path has been deprecated, please pass in a Service object](https://itsmycode.com/executable-path-has-been-deprecated/)

The ***`executable_path`*** is deprecated in Selenium 4 and above if you are still using the *`executable_path=chrome_driver_path`*) then you will get **DeprecationWarning: executable\_path has been deprecated, please pass in a Service object**

### [\[Solved\] Deprecationwarning: find\_element\_by\_\* commands are deprecated. please use find\_element() instead](https://itsmycode.com/find-element-by-commands-are-deprecated/)

If you use Selenium 4.0.0 or above and try to find the elements on the page using **the `find_element_by_*()`** method, you will get an error saying **DeprecationWarning: `find_element_by_*` commands are deprecated. Please use find\_element() instead**

### [Solving environment: failed with initial frozen solve. retrying with flexible solve](https://itsmycode.com/solving-environment-failed-with-initial-frozen-solve-retrying-with-flexible-solve/)

The **Solving environment: failed with initial frozen solve. retrying with flexible solve** occurs if you try to download any package that already exists and it breaks the anaconda environment.

### [Calculate Standard Error in R](https://itsmycode.com/calculate-standard-error-in-r/)

The ***standard error*** (***SE***) of a statistic is the ***standard deviation*** of its sampling distribution or an estimate of that ***standard deviation***. The standard error is calculated by **dividing the standard deviation by the square root of the number of sample data**.

### [SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape](https://itsmycode.com/syntaxerror-unicode-error-unicodeescape-codec-cant-decode-bytes-in-position-2-3-truncated-uxxxxxxxx-escape/)

The **SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape** occurs if you are trying to access a file path with a regular string.

### [How to enable CORS on Django REST Framework?](https://itsmycode.com/enable-cors-on-django-rest-framework/)

&#x20;If we are building an API layer using the Django REST framework and accessing these APIs in the front-end application we need to **enable the CORS on Django Rest Framework** otherwise we will get an error “**Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite**“

### [\[Solved\] AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’](https://itsmycode.com/numpy-ndarray-object-has-no-attribute-append/)

If you use the regular Python list **`append()`** method to add an element to the end of NumPy array, you will encounter **AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’.**

### [\[Solved\] SyntaxError: Positional argument follows keyword argument](https://itsmycode.com/positional-argument-follows-keyword-argument/)

&#x20;If you provide the keyword argument first followed by a positional argument, the Python interpreter will raise **SyntaxError: positional argument follows keyword argument**.

### [\[Solved\] ValueError: cannot convert float NaN to integer](https://itsmycode.com/cannot-convert-float-nan-to-integer/)

The **ValueError: cannot convert float NaN to integer** occurs when we attempt to convert the pandas DataFrame column from float to an integer where the column contains NaN value.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://itsmycode.gitbook.io/itsmycode/python-tutorials.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
