Python Tutorials

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

  • shutil module
  • os module
  • subprocess module
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.
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.
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.
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.
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.
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() 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.
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.
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.
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.
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
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.
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.
The KeyError in Padas occurs when you try to access the columns in pandas DataFrame, which does not exist, or you misspell them.
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
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\
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.
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.
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.
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.
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.
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.
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
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.
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.
The Python String title() method is a built-in function that returns a string where the first character of each word is uppercase.
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.
The Python String isdecimal() method is a built-in function that returns true if all the characters in a string are decimal.
The Python String isidentifier() method is a built-in function that returns true if the string is a valid identifier.
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
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.
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
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
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
There are 3 popular methods available to import CSV files into R.
  • Using read.csv() method
  • Using read_csv() method
  • Using fread() method
In this article, we will look at different ways to adding new column to existing DataFrame in Pandas.
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 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 a variable with examples.
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.
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
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.
There are four different methods to add a title to seaborn plots. Let us explore each of these methods in detail with examples.
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.
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.
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
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.
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,
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.
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.
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
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.
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.
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.
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 [email protected] version.
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.
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.
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.
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.
If you provide the keyword argument first followed by a positional argument, the Python interpreter will raise SyntaxError: positional argument follows keyword argument.
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’.
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.
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.
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’.
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() is a built-in function that returns the number of times the specified element occurs in the list.
Python List clear() is a built-in function that removes all the items and makes a list empty.
Python List remove() is a built-in function that removes the first occurrence element from the list.
Python List insert() is a built-in function that inserts the given element at a specified index.
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.
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.
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.
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
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
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.
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.
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.
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
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’.
If you provide the keyword argument first followed by a positional argument, the Python interpreter will raise SyntaxError: positional argument follows keyword argument.
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.
Last modified 7mo ago