C++ Program to Find Largest Number Among Three Numbers

C++ Program to Find Largest Number Among Three Numbers

In the previous article, we have discussed about C++ Program to Calculate Sum of First N Natural Numbers. Let us learn how to find Largest Number Among Three Numbers in C++ Program.

Method to find the largest number among 3 numbers in c++

In this article, we see different methods by which we can largest of 3 numbers using c++. Let see all the methods one by one.

Method 1-Using if statements

In this method, we use three if statements for all three numbers. In the first, if statement we will compare the first number with the second and third numbers and if it is greater than both the number then we will say number 1 is the largest. In the second if statement we will compare the second number with the first and third numbers and if it is greater than both the number then we will say number 2 is the largest. In the third, if statement we will compare the third number with the second and first numbers and if it is greater than both the number then we will say number 3 is the largest. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n1=10,n2=12,n3=9;
     if(n1 >= n2 && n1 >= n3)
        cout << "Largest number: " << n1;

    if(n2 >= n1 && n2 >= n3)
        cout << "Largest number: " << n2;
    
    if(n3 >= n1 && n3 >= n2)
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Here we see that 12 is the largest among the 3 numbers.

Method 2-Using if-else statement

There is a flaw in the first method because in the first method all the if statement runs. Suppose if we get that number 1 is the greatest is greatest in first if statement then in that case also all if statement runs. So to improve this we can use the if-else statement. In if-else statements, if one condition pass then we will not go to further statements. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if((n1 >= n2) && (n1 >= n3))
        cout << "Largest number: " << n1;
    else if ((n2 >= n1) && (n2 >= n3))
        cout << "Largest number: " << n2;
    else
        cout << "Largest number: " << n3;
    return 0;
}

Output

Largest number: 12

Method 3-Using nested if-else statement

This method is a more efficient version than the first two methods. Let write a code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     if (n1 >= n2) {
        if (n1 >= n3)
            cout << "Largest number: " << n1;
        else
            cout << "Largest number: " << n3;
    }
    else {
        if (n2 >= n3)
            cout << "Largest number: " << n2;
        else
            cout << "Largest number: " << n3;
    }

    return 0;
}

Output

Largest number: 12

Method 4-Using Ternary operator

The ternary operator is a way of using an if-else statement in one line.So by using the ternary operator we can reduce our code line with the same logic that we discuss above. Let write the code for this.

#include <iostream>
using namespace std;

int main() {
    
    int n1=10,n2=12,n3=9;
     int max = (n1 > n2) ?
          (n1 > n3 ? n1 : n3) :
          (n2 > n3 ? n2 : n3);
    cout << "Largest number among "
         << n1 << ", " << n2 << " and "
         << n3 << " is " << max << "." ;

    return 0;
}

Output

The largest number among 10, 12, and 9 is 12.

So these are the methods to find the largest among 3 numbers in c++.

C++ Program to Convert Octal Number to Decimal Number

C++ Program to Convert Octal Number to Decimal Number

In the previous article, we have discussed about C++ Program to Convert Decimal Number to Binary Number. Let us learn how to Convert Octal Number to Decimal Number in C++ Program.

Methods to Convert Octal Numbers to Decimal Numbers in C++

In this article, we will discuss different methods of converting octal to decimal numbers in c++. The list of the methods that we will discuss is given below.

Let discuss the basic idea for converting octal to a decimal number which will help us later in writing the code. Let discuss the approach with the help of an example. Suppose the octal number is 67 then its decimal form is 55. We will write 67 as 6*(8^1)+7*(8^0) which is equivalent to 55. So here we see we extract the digit of decimal number and multiply the digit with the power of 8 in increasing order. This means the first digit is multiplied with 8 to the power 0 while the second digit is multiplied with 8 to the power 1 and so on. So this is the intuition. Let’s discuss different methods to do it.

Method 1-Using Loop with arithmetic operator

In this approach, we will take the help of a loop and modulo(%) and division(/) operator to extract the digit of the binary number. When we extract the digit we will simply multiply the digit with a power of 8 and stored the result in the variable. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;


int convertOctalToDecimal(long long n)
{
    int decimalNumber = 0, i = 0, rem;
    while (n!=0)
    {
        rem = n%10;
        n /= 10;
        decimalNumber += rem*pow(8,i);
        i++;
    }
    return decimalNumber;
}

int main()
{
    long long n=67;
    cout << n << " in octal is " << convertOctalToDecimal(n) << " in decimal";
    return 0;
}

Output

67 in octal is 55 in decimal

Method 2-Using pre-defined function

In c++ there is a pre-defined function that is used to convert octal to decimal numbers. Here we are talking about stoi() function. Let us see what the stoi() function is.stoi() stands for the string to integer, it is a standard library function in C++ STL, it is used to convert a given string in various formats (like binary, octal, hex, or a simple number in string formatted) into an integer. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string n="67";
    cout << n << " in octal is " <<  stoi(n, 0, 8) << " in decimal";
    
    return 0;
}

Output

67 in octal is 55 in decimal

So these are the methods to convert octal numbers to decimal numbers in c++.

C++ Program to Find Factorial

C++ Program to Find Factorial

In the previous article, we have discussed about C++ Program to Display Fibonacci Series. Let us learn how to find factorial in C++ Program.

Methods to find factorial of a given number in c++

In this article, we discuss different methods of how we can find the factorial of a given number in c++. The list of methods that we will discuss is given below.

Before discussing the different methods let first understand what a factorial of the given number is. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.

Now we will discuss different methods to find the factorial of a given number.
<h3>Method 1-Iterative approach

As we discussed above that the factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. Hence we simply apply a for loop from 1 to a given number a store their multiplication in a variable and then print it. Let’s write the code for this.

#include <iostream>
using namespace std;

int main() {
    int res = 1, i,n=6;
    for (i = 1; i <= n; i++)
    {
        res *= i;
    }
    cout<<"Factorial of given number "<<n<<" is "<<res;
    
    return 0;
}

Output

Factorial of given number 6 is 720

Method 2-Using Recursion

Let analyze how we can calculate the factorial of a given number using recursion.

Suppose we want to calculate the factorial of the number 6. So we can write it as:-

factorial(6)=6*5*4*3*2*1  and if we analyze that 5*4*3*2*1 is also the factorial of number 5 so we can break factorial of 6 into factorial(6)=6* factorial(5) So that’s how we can call the recursive function. Let write the code for this.

#include <iostream>
using namespace std;
int factorial(unsigned int n)
{
    if (n == 0)
        return 1;
    return n * factorial(n - 1);
}
int main() {
    int n=6;
    cout<<"Factorial of given number "<<n<<" is "<<factorial(6);
    
    return 0;
}

Output

Factorial of given number 6 is 720

Method 3-Using Dynamic Programming

The problem with the above recursive is that we have to call the recursive function for a particular number multiple times. Here Dynamic programming solves this problem. Instead of calling a recursive function for a given number again and again we store the result of that number in an array and when this number we directly return its value from the array instead of calculating the value again. Let’s write the code for this.

#include <iostream>
using namespace std;
int result[1000] = {0};
int factorial(int n) {
   if (n >= 0) {
      result[0] = 1;
      for (int i = 1; i <= n; ++i) {
         result[i] = i * result[i - 1];
      }
      return result[n];
   }
}
int main() {
   int n=6;
   cout<<"Factorial of a given number "<<n<<" is "<<factorial(n);
   return 0;
}

Output

Factorial of a given number 6 is 720

So these are the methods to calculate the factorial of a given number in c++.

INSERT Record if NOT EXISTS in MySQL

Methods to insert records if not exist in MySQL

In this article, we discuss how to insert single or multiple records in SQL tables if they are not present. If records are already present then no updation occurs.

Before going to the actual content first let create a table and insert some dummy data into it.

CREATE TABLE student_details(
    student_id INT auto_increment,
   student_name VARCHAR(255),
   student_address VARCHAR(255),
    primary key (student_id));
INSERT INTO student_details (student_name,student_address) 
 VALUES("Mayank","Kolkata"),
("Raj","Delhi"),
("Abhay","Delhi"),
("Aman","Jaipur"),    
("Rahul","Mumbai"),
("Shubh","Merrut");
select * from student_details;

Output

student_id student_name student_address
1 Mayank Kolkata
2 Raj Delhi
3 Abhay Delhi
4 Aman Jaipur
5 Rahul Mumbai
6 Shubh Merrut

So this is our student_details table.

Now we will see how to insert single or multiple records if not exist in the table. Let first see the syntax or sample SQL query to do this task after that we will implement the query on our table.

INSERT NOT EXISTS Syntax

If a subquery returns any rows at all, NOT EXISTS subquery is FALSE. It means that if the subquery in the NOT EXIST clause is TRUE, it will return no rows.

Syntax:INSERT INTO table_name (column1, column2, ....)                                           SELECT * FROM (SELECT value1, value2,....) AS temp                                          WHERE NOT EXISTS (<conditional_subquery>);

table_name: It is the name of that table where we want to insert the data.

<conditional_subquery>: It is the sub-query including a select statement to get the row with a particular condition.

INSERT single record if NOT EXISTS in MySQL

Now with the help of the above query, we will see how to insert a single record if it is NOT EXISTS in MySQL.

INSERT INTO student_details (student_name,student_address) 
SELECT * FROM (SELECT 'Manish' AS student_name, 'Agra' AS student_address) AS temp 
WHERE NOT EXISTS ( SELECT student_name FROM student_details WHERE student_name = 'Manish' ) LIMIT 1

Output

student_id student_name student_address
1 Mayank Kolkata
2 Raj Delhi
3 Abhay Delhi
4 Aman Jaipur
5 Rahul Mumbai
6 Shubh Merrut
7 Manish Agra

Here we see that one record with student_name=’Manish’ and student_address=’Agra’ is inserted.

Suppose we will fire this query again. Let see what happens.

 0 rows inserted. (Query took 0.0012 seconds.)

When we try to execute this query again we see that this time no record is inserted because the record is already present in the SQL table. So we can say that this query only inserts records when NOT EXIST in MySQL.

INSERT multiple records if NOT EXISTS in MySQL

What if we have more than one record to be inserted, and before every insert, we want to ensure that the record with the same column value does not exist. Let see how to write an SQL query for this.

INSERT INTO student_details (student_name, student_address) 
SELECT student_name, student_address FROM 
( SELECT student_name , student_address FROM 
( SELECT 'Ravi' as student_name , 'Shimla' as student_address ) AS temp_1 
WHERE NOT EXISTS ( SELECT student_name FROM student_details WHERE student_name = 'Ravi' ) 
UNION ALL 
SELECT student_name, student_address FROM ( SELECT 'Raju' as student_name , 'Bandra' as student_address ) AS temp_2 WHERE NOT EXISTS ( SELECT student_name FROM student_details WHERE student_name = 'Raju' ) ) 
alias_student_details

Output

student_id student_name student_address
1 Mayank Kolkata
2 Raj Delhi
3 Abhay Delhi
4 Aman Jaipur
5 Rahul Mumbai
6 Shubh Merrut
7 Manish Agra
8 Ravi Shimla
9 Raju Bandra

So here we see another 2 records inserted in the SQL table. So we see how to insert multiple or single records if NOT EXIST in MySQL.

C++ get file name – How to Get Filename From a Path With or Without Extension in C++

How to Get Filename From a Path With or Without Extension in C++

Methods to get filename from a path with or without extension in c++

C++ get file name: In this article, we discuss the different methods to get filename from a path with or without extension in c++. Let’s see c get filename from path with extension, c get filename from path without extension, c remove path from filename, c find all files in directory with extension, c iterate through files in a directory, c filesystempath to string, c++ get filename from path, c get file path, c++ iterate through files in a directory, c++ get file path, c filesystem::path to string, How to get filename from a path with or without extension in c++. The method that we discuss are given below:-

Let’s first understand what we will be going to do in this article. Suppose there is a path name p="/home/user/c++/program.c++" then in this example filename with extension is program.c++ and filename without extension is program. So we will be writing code in c++ to do this task.

Let’s understand all the methods one by one.

Method 1-Using string functions

C++ get file extension: In this method, we use the string in c++ to do the task. We will use different functions that are used in c++ strings to extract the filename. Let see this with the help of an example.

#include <iostream>
#include <string>

using std::string;
string getFileNameWithExtension(const string& s) {
char sep = '/';
#ifdef _WIN32
sep = '\\';
#endif
size_t i = s.rfind(sep, s.length());
if (i != string::npos) 
{
string filename = s.substr(i+1, s.length() - i);
string rawname = filename.substr(0, s.length()); 
return(rawname);
}

return("");
}

string getFileNameWithoutExtension(const string& s) {
char sep = '/';
#ifdef _WIN32
sep = '\\';
#endif
size_t i = s.rfind(sep, s.length());
if (i != string::npos) 
{
string filename = s.substr(i+1, s.length() - i);
size_t lastindex = filename.find_last_of("."); 
string rawname = filename.substr(0, lastindex); 
return(rawname);
}

return("");
}

int main() {

string path = "/home/user/c++/program.c++";
string filename_with_extension = getFileNameWithExtension(path);
string filename_without_extension= getFileNameWithoutExtension(path);
std::cout << "The file name with extension  is \"" << filename_with_extension  << "\"\n";
std::cout << "The file name without extension  is \"" << filename_without_extension << "\"\n";
}

Output

The file name with extension is "program.c++"
The file name without extension is "program"

Method 2-Using C++17 Filesystem library

Java get filename without extension: The Filesystem library provides facilities for performing operations on file systems and their components, such as paths, regular files, and directories. So here we will use the Filesystem library to get filename from a path with and without extension. Let’s write code for this.

#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    std::cout << "The file name with extension  is " <<fs::path( "/home/user/c++/program.c++" ).filename() << '\n';
    std::cout << "The file name without extension  is " <<fs::path( "/home/user/c++/program.c++" ).stem() << '\n';
        
}

Output

The file name with extension is "program.c++"
The file name without extension is "program"

So these are the methods to get filename with and without extension in c++.

Add column to csv python – Python: Add a Column to an Existing CSV File

Python Add a Column to an Existing CSV File

Methods to add a column to an existing CSV File

Add column to csv python: In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter  classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

We also include these for beginners:

  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Python csv write to specific row and column
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Python add a column to an existing csv file
  • Python add a new column to csv
  • Python add csv column to list
  • Python pandas append column to csv
  • Add a line to a csv file python

Original CSV file content

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
  • Method 1-Add a column with the same values to an existing CSV file

Python add column to csv: In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer
from csv import reader
default_text = 'New column'
# Open the input_file in read mode and output_file in write mode
with open('example1.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    # Create a csv.reader object from the input file object
    csv_reader = reader(read_obj)
    # Create a csv.writer object from the output file object
    csv_writer = writer(write_obj)
    # Read each row of the input csv file as list
    for row in csv_reader:
        # Append the default text in the row / list
        row.append(default_text)
        # Add the updated row / list to the output file
        csv_writer.writerow(row)
output_data=pd.read_csv('output_1.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New column
0 16.99 1.01 Female No Sun Dinner 2 New column
1 10.34 1.66 Male No Sun Dinner 3 New column
2 21.01 3.50 Male No Sun Dinner 3 New column
3 23.68 3.31 Male No Sun Dinner 2 New column
4 24.59 3.61 Female No Sun Dinner 4 New column

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

  •  Method 2-Add a column to an existing CSV file, based on values from other columns

How to add a new column to a csv file using python: In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1]))
output_data=pd.read_csv('output_2.csv')
output_data.head()

Output

total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

Explanation:

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

  • Method 3-Add a list as a column to an existing csv file

Python csv write column: In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer
from csv import reader
def add_column_in_csv(input_file, output_file, transform_row):
    """ Append a column in existing csv using csv.reader / csv.writer classes"""
    # Open the input_file in read mode and output_file in write mode
    with open(input_file, 'r') as read_obj, \
            open(output_file, 'w', newline='') as write_obj:
        # Create a csv.reader object from the input file object
        csv_reader = reader(read_obj)
        # Create a csv.writer object from the output file object
        csv_writer = writer(write_obj)
        # Read each row of the input csv file as list
        for row in csv_reader:
            # Pass the list / row in the transform function to add column text for this row
            transform_row(row, csv_reader.line_num)
            # Write the updated row / list to the output file
            csv_writer.writerow(row)
l=[]
l.append("New Column")
rows = len(data.axes[0])
for i in range(rows):
    val=i+1
    l.append(val)
add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1]))
output_data=pd.read_csv('output_3.csv')
output_data.head()

Output

total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

Explanation

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index  line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Test yourself:

  1. Write to a specific column in csv python pandas?
  2. Write to specific column csv python?
  3. How do i add a column to an existing csv file in python?
  4. How to add column in existing csv file using python?

 

C++ reverse number – C++ Program to Reverse a Number

C++ Program to Reverse a Number

C++ reverse number: In the previous article, we have discussed about C++ Program to Calculate Power of a Number. Let us learn how to Reverse a Number in C++ Program.

Methods to Reverse a Number in C++

How to reverse a number c++: In this article, we will see different methods of how we can reverse a number in c++. Let see all the methods one by one.

Method1-Using while loop

get4321.com: In this method, we extract the digit of a number a through this we will make a new number which is the reverse of the given number. Let’s write the code to understand this.

#include <iostream>
using namespace std;

int main() {
    int n, reversedNumber = 0, remainder;
    n=1234;
    while(n != 0) {
        remainder = n%10;
        reversedNumber = reversedNumber*10 + remainder;
        n /= 10;
    }
    cout << "Reversed Number = " << reversedNumber;

    return 0;
}

Output

Reversed Number = 4321

Now lets see how this work. Suppose our number is 1234.

Iteration1- remainder-4  reversedNumber=(0*10)+4=4    number=1234/10=123

Iteration2- remainder-3  reversedNumber=(4*10)+3=43    number=123/10=12

iteration3- remainder-2   reversedNumber=(43*10)+2=432   number=12/10=1

iteration4- remainder-1    reversedNumber=(432*10)+1=4321   number=1/10=0

As the number become 0 so we come out of the loop and we get 4321 as our reversed number.

Method 2-By converting number to string

In this method first, we convert our number to a string. For this we use inbuilt method in c++ to_string().Then we reverse the string using the reverse() method in c++. And then we convert that reverse string again to a number using stoi() method. Let write the code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, reversedNumber = 0, remainder;
    n=1234;
    string s=to_string(n);
    reverse(s.begin(),s.end());
    n=stoi(s);
    cout << "Reversed Number = " << n;
    return 0;
}

Output

Reversed Number = 4321

So these are the methods to reverse a number in c++.

Python zip multiple files – Python: How to create a zip archive from multiple files or Directory

Method to create zip archive from multiple files or directory in python

Python zip multiple files: In this article, we discuss how we can create a zip archive of multiple files or directories in python. To understand this let us understand about ZipFile class.

ZipFile class

Create zip file python: To execute this program we have to import ZipFile class of zipfile module.ZipFile is a class of zipfile modules for reading and writing zip files.

syntax: zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)

Create a zip archives of multiples file

    • Method 1:Without using with statement

Let us first write the program and then see how code works.

from zipfile import ZipFile
# create a ZipFile object
zipObj = ZipFile('sample.zip', 'w')
# Add multiple files to the zip
zipObj.write('file1.txt')
zipObj.write('file2.txt')
# close the Zip File
zipObj.close()

Output

Directory structure before the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:06 216 zip.py

Directory structure after the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:09 216 zip.py

Here we clearly see that a zip file is created.

Let see how the program works. First, we create a ZipFile object bypassing the new file name and mode as ‘w’ (write mode). It will create a new zip file and open it within the ZipFile object. Then we use Call write() function on ZipFile object to add the files in it and then call close() on ZipFile object to Close the zip file.

  • Method 2:Using with statement

Python create zip file: The difference between this and the previous method is that when we didn’t use with the statement then we have to close the zip file when the ZipFile object goes out of scope but when we use with statement the zip file automatically close when the ZipFile object goes out of scope. Let see the code for this.

from zipfile import ZipFile
# Create a ZipFile Object
with ZipFile('sample2.zip', 'w') as zipObj:
   # Add multiple files to the zip
   zipObj.write('file1.txt')
   zipObj.write('file2.txt')

Output

Directory structure before the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:21 429 zip.py

Directory structure after the execution of the program

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:24 239 sample2.zip
-a---- 10-06-2021 19:24 429 zip.py

Here we see that another zip file is created.

Create a zip archive of the directory

Python zip directory: To zip selected files from a directory we need to check the condition on each file path while iteration before adding it to the zip file. As here we work on directory and file so we also have to import os module. Let see the code for this.

from zipfile import ZipFile
import os
from os.path import basename
# create a ZipFile object
dirName="../zip"
with ZipFile('sampleDir.zip', 'w') as zipObj:
   # Iterate over all the files in directory
   for folderName, subfolders, filenames in os.walk(dirName):
       for filename in filenames:
           #create complete filepath of file in directory
           filePath = os.path.join(folderName, filename)
           # Add file to zip
           zipObj.write(filePath, basename(filePath))

Output

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10-06-2021 18:41 14 file1.txt
-a---- 10-06-2021 18:41 15 file2.txt
-a---- 10-06-2021 19:09 239 sample.zip
-a---- 10-06-2021 19:24 239 sample2.zip
-a---- 10-06-2021 21:44 2796 sampleDir.zip
-a---- 10-06-2021 19:24 429 zip.py
-a---- 10-06-2021 21:44 506 zipdir.py

Here we see that the sampleDir.zip file is created.

Pandas read csv delimeter – Read Csv File to Dataframe With Custom Delimiter in Python

Different methods to read CSV files with custom delimiter in python

Pandas read csv delimeter: In this article, we will see what are CSV files, how to use them in pandas, and then we see how and why to use custom delimiter with CSV files in pandas.

CSV file

Pandas read csv separator: A simple way to store big data sets is to use CSV files (comma-separated files).CSV files contain plain text and is a well know format that can be read by everyone including Pandas. Generally, CSV files contain columns separated by commas, but they can also contain content separated by a tab, or underscore or hyphen, etc. Generally, CSV files look like this:-

total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
23.68,3.31,Male,No,Sun,Dinner,2
24.59,3.61,Female,No,Sun,Dinner,4

Here we see different columns and their values are separated by commas.

Use CSV file in pandas

Read csv separator: read_csv() method is used to import and read CSV files in pandas. After this step, a CSV file act as a normal dataframe and we can use operation in CSV file as we use in dataframe.

syntax:  pandas.read_csv(filepath_or_buffer, sep=‘, ‘, delimiter=None, header=‘infer’, names=None, index_col=None, ….)

',' is default separator in read_csv() method.

Let see this with an example

import pandas as pd
data=pd.read_csv('example1.csv')
data.head()

Output

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

Why use separator or delimiter with read_csv() method

Read_csv separator: Till now we understand that generally, CSV files contain data separated data that is separated by comma but sometimes it can contain data separated by tab or hyphen, etc. So to handle this we use a seperator. Let understand this with the help of an example. Suppose we have a CSV file separated by an underscore and we try to read that CSV file without using a separator or with using default separator i.e. comma. So let see what happens in this case.

"total_bill"_tip_sex_smoker_day_time_size
16.99_1.01_Female_No_Sun_Dinner_2
10.34_1.66_Male_No_Sun_Dinner_3
21.01_3.5_Male_No_Sun_Dinner_3
23.68_3.31_Male_No_Sun_Dinner_2
24.59_3.61_Female_No_Sun_Dinner_4
25.29_4.71_Male_No_Sun_Dinner_4
8.77_2_Male_No_Sun_Dinner_2

Suppose this is our CSV file separated by an underscore.

total_bill_tip_sex_smoker_day_time_size
0 16.99_1.01_Female_No_Sun_Dinner_2
1 10.34_1.66_Male_No_Sun_Dinner_3
2 21.01_3.5_Male_No_Sun_Dinner_3
3 23.68_3.31_Male_No_Sun_Dinner_2
4 24.59_3.61_Female_No_Sun_Dinner_4

Now see when we didn’t use a default separator here how unordered our data look like. So to solve this issue we use Separator. Now we will see when we use a separator to underscore how we get the same data in an ordered manner.

import pandas as pd 
data=pd.read_csv('example2.csv',sep = '_',engine = 'python') 
data.head()

Output

total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

So this example is sufficient to understand why there is a need of using a separator of delimiter in pandas while working on a CSV file.

Now suppose there is a CSV file in while data is separated by multiple separators. For example:-

totalbill_tip,sex:smoker,day_time,size
16.99,1.01:Female|No,Sun,Dinner,2
10.34,1.66,Male,No|Sun:Dinner,3
21.01:3.5_Male,No:Sun,Dinner,3
23.68,3.31,Male|No,Sun_Dinner,2
24.59:3.61,Female_No,Sun,Dinner,4
25.29,4.71|Male,No:Sun,Dinner,4

Here we see there are multiple seperator used. So here we can not use any custom delimiter. To solve this problem regex or regular expression is used. Let see with the help of an example.

import pandas as pd 
data=pd.read_csv('example4.csv',sep = '[:, |_]') 
data.head()

Output

totalbill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4

When we notice we pass a list of separators in the sep parameter that is contained in our CSV file.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Python tuple to array – Create NumPy Array from List, Tuple or List of Lists in Python

Methods to create NumPy array from list, tuple, or list of lists in Python

Python tuple to array: In this article, we will discuss some basics of NumPy array and how to create NumPy array from lists, tuples, and Lists of lists in python.

NumPy

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it in our program and then we can easily use the functionality of NumPy in our program.

numpy.array()

This method is going to be widely used in our program so it will be beneficial to study this method in advance so that it will be easy for us to understand the concepts. This method helps us to create a numpy array from already defined data structures in python like lists, tuples, and nested lists.

Syntax: numpy.array(object, dtype=None, copy=True, order=‘K’, subok=False, ndmin=0)

This method returns a numpy array.

numpy.asarray()

This method helps us to create a numpy array from already defined data structures in python like lists, tuples, and nested lists.

Syntax: numpy.asarray(arr, dtype=None, order=None)

Difference between numpy.array() and numpy.asarray()

The major difference between both the methods is that numpy.array() will make a duplicate of original copy while the numpy.asarray() make changes in the original copy.

Create a numpy array from a list

  • Method 1-Using numpy.array()

In this method, we will see how we can create a numpy array from the list in python. When we look at the parameter of this method we see that in the parameter one parameter is an object that clearly gives us a hint that we can pass our list in this method and we may get our output in the form of NumPy array. Let us see this method with the help of an example.

l=[1,2,3,4,5,6]
array=np.array(l)
print(array)
print(type(array))

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>

Here we see how we easily create our numpy array from the list using numpy.array() method.

  • Method 2-Using numpy.asarray()

This method also works in the same way as numpy.array() work.We just simply pass our list object in the function and we will get our numpy array. Let see this with an example.

l=[1,2,3,4,5,6]
array=np.asarray(l)
print(array)
print(type(array))

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>

Create a numpy array from a tuple

  • Method 1-Using numpy.array()

Here the procedure is the same as we discuss in the case of lists. Here instead of a list, we have to pass out a tuple and we get our numpy array. Let see this with the help of an example.

t=(1,2,3,4,5,6)
array=np.array(t)
print(array)
print(type(array))

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>
  • Method 2-Using numpy.asarray()

Just like we use this method in the case of lists here we also use this in a similar way. But here instead of using the list, we pass tuple as an object. Let see this with the help of an example.

t=(1,2,3,4,5,6)
array=np.asarray(t)
print(array)
print(type(array))

Output

[1 2 3 4 5 6]
<class 'numpy.ndarray'>

Create a 2d Numpy array from a list of list

numpy. array() method will also work here and the best part is that the procedure is the same as we did in the case of a single list.In this case, we have to pass our list of lists as an object and we get our output as a 2d array.Let see this with the help of an example.

l=[[1,2,3],[4,5,6]]
array=np.asarray(l)
print(array)
print(type(array))

Output

[[1 2 3]
 [4 5 6]]
<class 'numpy.ndarray'>

So these are the methods to create numpy array from list,tuples and lists of lists.