Friday, December 11, 2020

Input from User in Python – input() function

If you have to take user input from keyboard in Python that can be done using input() function. Python input() function takes the entered value and returns it as a string once user presses Enter.

Syntax of input() function

The syntax of Python input() function is

input(msg)

Here msg is the optional string that is displayed on the console.

User input in Python example

val = input('Please enter your name: ')
print('Entered Value- ', val)
Output
Please enter your name: knpcode
Entered Value- knpcode

Input as number in Python

Note that input() function always returns entered value as string. If you want to get the value as integer or float you need to convert it explicitly.

val = input('Please enter a number: ')
# Convert to int
val = int(val)
# now use in arithmetic operation
print(val+5)
Output
Please enter a number: 8
13

You can use int() function along with the input() function to shorten the code-

val = int(input('Please enter a number: '))
# now use in arithmetic operation
print(val+5)

For float numbers you can use float() function

val = float(input('Please enter a number: '))
# now use in arithmetic operation
print(val+5)

Multiple values as input in Python

You can write separate input() functions to take more than one inputs from user. But Python provides a shorter version by using for loop along with input() function to take multiple inputs. Entered values are parsed as separate values by using split() method which considers space as delimiter by default. Therefore separate the separate inputs by space.

num1, num2, num3 = [int(x) for x in input('Please enter three integers: ').split()]
print('Sum of entered numbers-', (num1+num2+num3))
Output
Please enter three integers: 4 5 6
Sum of entered numbers- 15

That's all for the topic Input from User in Python – input() function. If something is missing or you have something to share about the topic please write a comment.


You may also like

Thursday, December 10, 2020

Python Program to Append to a File

In the post Python Program to Write a File we saw options to write to a file in Python but that has the drawback of overwriting the existing file. If you want to keep adding content to an existing file you should use append mode to open a file. In this tutorial we’ll see options to append to a file in Python.

Append mode in Python I/O

To append data to a file i.e. adding content to the end of an existing file you should open file in append mode (‘a’). If the file doesn’t exist it will create a new file for writing content.

Appending to a file in Python

Following method opens the passed file in append mode and then adds content to the end of the file.

def append_file(fname):
  with open(fname, 'a') as f:
    f.write('This line is added to the already existing content')

Using ‘a+’ mode to write and read file

Following program opens a file in ‘a+’ mode for both appending and reading. Program also uses tell() method to get the current position of the file pointer and seek() method to move to the beginning of the file.

def append_file(fname):
  with open(fname, 'a+') as f:
    f.write('This line is added to the already existing content')
    f.flush()
    print("Current position of file pointer- ", f.tell())
    f.seek(0, 0)
    s = f.read()
    print('Content- ', s)

That's all for the topic Python Program to Append to a File. If something is missing or you have something to share about the topic please write a comment.


You may also like

Wednesday, December 9, 2020

Python Program to Write a File

In this tutorial we’ll see different options to write to a file in Python.

  1. Using write() method you can write the passed string to a file.
  2. Using writelines(lines) method you can write a list of lines.
  3. Writing file in binary mode.

1. Using write() method for file writing in Python

f.write(string) writes the contents of string to the file and returns the number of characters written. For writing to a file in Python file should be opened in write mode. Note that opening in write mode (‘w’) will either create the file if it doesn’t exist or overwrite the file if already exists.

def write_file(fname):
  try:
    f = open(fname, 'w')
    f.write("This is Line 1.\n")
    f.write("This is Line 2.")
  finally:
    f.close()


write_file("F:/knpcode/Python/test.txt")

Here write_file() method takes the file path as argument and opens that file in write mode. Two lines are written to the file and then the file is closed.

Another way to open the file is using with keyword which automatically closes the file. Using with open is preferred as it makes code shorter.

def write_file(fname):
  with open (fname, 'w') as f:
    chars_written = f.write("This is Line 1.\n")
    print('Characters written to the file', chars_written);
    f.write("This is Line 2.")

As you can see now try-finally block is not required as with open automatically closes the file once file operations are done.

If you want to write any other type of object then it has to converted to the string (in text mode) or a bytes object (in binary mode) before writing it to the file. For example in the following program we want to write a tuple to the file for that it has to be converted to str first.

def write_file(fname):
  with open(fname, 'w') as f:
    value = ('One', 1)
    s = str(value)  # convert the tuple to string
    f.write(s)

2. Using writelines(lines) method you can write a list of lines.

If you have a list of lines then you can use writelines() method to write it.

def write_file(fname):
  with open(fname, 'w') as f:
    lines = ["This is the first line\n", "This is the second line\n", "This is the third line"]
    f.writelines(lines)

3. Using ‘w+’ mode to write and read file.

Following program opens a file in 'w+' mode for both writing and reading. Program also uses tell() method to get the current position of the file pointer and seek() method to move to the beginning of the file.

def write_read_file(fname):
  with open(fname, 'w+') as f:
    f.write("This is the first line.\n")
    f.write("This is the second line.\n")
    f.flush()
    print("Current position of file pointer- ", f.tell())
    f.seek(0, 0)
    s = f.read()
    print('Content- ', s)

4. Writing a binary file in Python

If you want to write a binary file you need to open file in ‘wb’ mode. In the following Python program to copy an image an image file is opened in binary mode and then written to another file.

def copy_file():
  try:
    # Opened in read binary mode
    f1 = open('F:/knpcode/Java/Java Collections/collection hierarchy.png', 'rb')
    # Opened in write binary mode
    f2 = open('F:/knpcode/Python/newimage.png', 'wb')
    b = f1.read()
    f2.write(b)
    print('Coying image completed...')
  finally:
    f1.close()
    f2.close()

That's all for the topic Python Program to Write a File. If something is missing or you have something to share about the topic please write a comment.


You may also like

Tuesday, December 8, 2020

Python Program to Read a File

In this tutorial we’ll see different options to read a file in Python.

  1. Using read() method you can read the whole file.
  2. Using readline() and readlines() methods you can read file line by line.
  3. More efficient way to read file line by line is to iterate over the file object.
  4. Reading file in binary mode.

1. Using read() method

f.read(size) method reads and returns size bytes. If size argument is not passed or negative, the entire contents of the file will be read and returned.

def read_file(fname):
  try:
    f = open(fname, 'r')
    s = f.read()
    print(s)
  finally:
    f.close()


read_file('F:\\knpcode\\abc.txt')

Here read_file() function is written to read a file which takes file path as argument. File is opened using open() function in read mode and read using read() method. You should always close the file to free the resources which is done in the finally block.

Another way to open the file is using with keyword which automatically closes the file. Using with open is preferred as it makes code shorter.

def read_file(fname):
  with open(fname, 'r') as f:
    s = f.read(9)
    print(s) 

2. Using readline() method to read a file in Python.

f.readline() reads a single line from the file.

def read_file(fname):
  with open(fname, 'r') as f:
    s = f.readline()
    print('Content- ', s)
3. Using readlines() method.

f.readlines() method reads all the lines of a file in a list.

def read_file(fname):
  with open(fname, 'r') as f:
    s = f.readlines()
    print('Content- ', s)

You can also read all the lines of a file by using list(f) function.

def read_file(fname):
  with open(fname, 'r') as f:
    s = list(f)
    print('Content- ', s)

4. Looping over the file object

read(size) or f.readlines() read all the content of the file making it inefficient if the file is large as the whole file will be loaded into the memory. More memory efficient and fast way to read lines from a file is by looping over the file object.

def read_file(fname):
  with open(fname, 'r') as f:
    for line in f:
      # Empty string (‘’) is the EOF char
      print(line, end='')

Similar logic to read the file line by line in Python can also be written using the readline() method.

def read_file(fname):
  with open(fname, 'r') as f:
    line = f.readline()
    while line != '':
      print(line, end='')
      line = f.readline()

5. Reading a binary file in Python.

If you want to read a binary file you need to open file in ‘rb’ mode. In the following Python program to copy an image an image file is opened in binary mode and then written to another file.

def copy_file():
  try:
    f1 = open('F:/knpcode/Java/Java Collections/collection hierarchy.png', 'rb')
    f2 = open('F:/knpcode/Python/newimage.png', 'wb')
    b = f1.read()
    f2.write(b)
    print('Coying image completed...')
  finally:
    f1.close()
    f2.close()

That's all for the topic Python Program to Read a File. If something is missing or you have something to share about the topic please write a comment.


You may also like

Wednesday, December 2, 2020

Spring Boot With Docker Example

In this tutorial you’ll see how to build a Docker image for running a Spring Boot application. We’ll create a basic DockerFile to dockerize a Spring Boot MVC application where view is created using Thymeleaf.

Maven Dependencies

Since we are creating a web application so we need a spring-boot-starter-web, for Thymeleaf we need spring-boot-starter-thymeleaf, spring-boot-maven-plugin is also added to our pom.xml. This plugin provides many convenient features-

  • It helps to create an executable jar (über-jar), which makes it more convenient to execute and transport your service.
  • It also searches for the public static void main() method to flag the class having this method as a runnable class.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.knpcode</groupId>
  <artifactId>SprinBootProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringBootProject</name>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.0.RELEASE</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
     </dependency>
     <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Classes for Spring Boot Web Application

We’ll add a simple controller for our web application.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MessageController {
  @GetMapping("/")
  public String showMessage(Model model) { 
    model.addAttribute("msg", "Welome to Docker");
    return "message";
  }
}
View class (Thymeleaf template)

In src/main/resources added a new folder Templates and in that created a message.html file.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Spring Boot With Docker</title>
</head>
<body>
 <div>
    <p th:text="${msg}"></p>
 </div>
</body>
</html>

Application Class

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootProjectApp {
  public static void main(String[] args) {
    SpringApplication.run(SpringBootProjectApp.class, args);
  }
}
Running the application

You can run this Spring Boot web application as a stand alone Java application but we'll run it by creating an executable jar.

For creating a completely self-contained executable jar file run mvn package from the command line. Note that you should be in your Spring Boot project directory.

knpcode:SprinBootProject$ mvn package

To run application using the created jar, you can use the java -jar command, as follows-

java -jar target/SprinBootProject-0.0.1-SNAPSHOT.jar

But we’ll do the samething by creating a DockerFile.

DockerFile

For running in your application in Docker container you need to create an image which is a read-only template with instructions for creating a Docker container.

For creating Docker image you create a Dockerfile which is a text file with a simple syntax for defining the steps needed to create the image and run it. Each instruction in a Dockerfile creates a layer in the image.

Create a text file with in your project directory named DockerFile and copy the following text in it.

FROM openjdk:8-jdk-alpine

ARG JAR_FILE=target/SprinBootProject-0.0.1-SNAPSHOT.jar

COPY ${JAR_FILE} app.jar

ENTRYPOINT ["java","-jar","/app.jar"]
  1. Often, an image is based on another image, with some additional customization. This is true in our case too and the base image used here is openjdk:8-jdk-alpine This image is based on the popular Alpine Linux project which is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general.
  2. Then assign a name to the jar path.
  3. Copy jar file.
  4. Execute jar using the ENTRYPOINT instruction by providing arguments in the following form- ENTRYPOINT ["executable", "param1", "param2"] Which makes it equivalent to java -jar target/SprinBootProject-0.0.1-SNAPSHOT.jar

Create a docker image

You can create a Docker image by running command in the following form-

sudo docker build -t name:tag .

For our project command to create a docker image-

sudo docker build -t sbexample:1.0 .

. means using the current directory as context

tag the image as sbexample:1.0

To create a container (run an image)

The docker run command must specify an image to derive the container from.

sudo docker run -d -p 8080:8080 sbexample:1.0

Here options are-

-d To start a container in detached mode (to run the container in the background)

-p Publish all exposed ports to the host interfaces

If every thing works fine then you will have a dockerized Spring Boot application at this point which you can access by typing URL http://localhost:8080/ in a browser

Spring Boot With Docker

If you want to see the running containers use following command

sudo docker ps

To stop a running container use following command

sudo docker stop container_id

That's all for the topic Spring Boot With Docker Example. If something is missing or you have something to share about the topic please write a comment.


You may also like