Here, You can read basic concepts of machine learning and enhance your level manifolds.
I/O Functions

Input / Output Functions

Python provides various built-in functions to perform input and output operations. In this section, you will learn some of the most commonly used input/output functions in Python:

  1. print() function: The print() function is used to output data to the console. It can be used to output strings, numbers, variables, and expressions.

    EXAMPLE:

    print("Hello World!")

    OUTPUT:

    Hello World!

  2. input() function: The input() function is used to accept user input from the console. The input function takes one optional parameter, which is the prompt string to be displayed on the console.

    EXAMPLE:

    name = input("Enter your name: ")
    print("Hello, " + name + "!")

    OUTPUT:

    Enter your name: Yuvi
    Hello, Yuvi!

  3. open() function: The open() function is used to open a file and return a file object. It takes two arguments, the filename and the mode in which the file is opened. The modes are 'r' for reading, 'w' for writing, and 'a' for appending.

    EXAMPLE:

    file = open("studentData.txt", "w")
    file.write("This file contains student Data.")
    file.close()
    file = open("studentData.txt", "r")
    print(file.read())
    file.close()

    OUTPUT:

    This file contains student Data.

  4. write() method: The write() method is used to write data to a file. It takes a string as its argument and writes it to the file.
  5. EXAMPLE:

    file = open("info.txt", "w")
    file.write("Student Data....")
    file.close()

  6. read() method: The read() method is used to read data from a file. It takes an optional parameter that specifies the number of bytes to read. If no parameter is specified, it reads the entire file.

    EXAMPLE:

    file = open("info.txt", "r")
    print(file.read())
    file.close()

    OUTPUT:

    Student Data....

  7. with statement: The with statement is used to open a file and ensure that it is closed properly after the file operations are completed. It automatically closes the file even if an exception occurs.

    EXAMPLE:

    with open("info.txt", "r") as f1:
    print(f1.read())

    OUTPUT:

    Student Data....

  8. seek() method: The seek() method is used to change the file pointer to a specific position in the file. It takes an offset and a reference point as its arguments. The reference point can be either 0, 1, or 2, which represents the beginning, current position, or end of the file, respectively.

    EXAMPLE:

    file = open("info.txt", "r")
    file.seek(5)
    print(file.read())
    file.close()

    Student Data....

Advertisement

Advertisement