In Python, Input and Output (I/O) refers to the mechanisms for interacting with a program—taking input from users or files and displaying or saving output. Python provides straightforward and versatile tools for handling I/O operations.


Standard Input and Output

  1. Input: input() Function

    • The input() function is used to take user input as a string.
    • Example:
      name = input("Enter your name: ") age = input("Enter your age: ") print(f"Hello, {name}! You are {age} years old.")
    • Note: Use int() or float() to convert input to numbers if needed:
      num = int(input("Enter a number: ")) print(f"Square of {num} is {num ** 2}")
  2. Output: print() Function

    • The print() function displays information to the console.

    • Example:

      print("Hello, World!") name = "Alice" print(f"Welcome, {name}.")
    • Formatting output:

      print("Name: {}, Age: {}".format("Bob", 25)) # Using format() print(f"Name: {'Bob'}, Age: {25}") # Using f-strings

File I/O in Python

Python’s open() function is used to read from and write to files.

  1. Opening a File:

    • Syntax: open(file_name, mode)
      • Modes:
        • 'r': Read (default).
        • 'w': Write (overwrites file).
        • 'a': Append.
        • 'b': Binary mode.
        • 'x': Create a new file.
  2. Reading a File:

    with open("example.txt", "r") as file: content = file.read() # Reads entire file print(content)
    • Other methods:
      • readline(): Reads one line.
      • readlines(): Reads all lines into a list.
  3. Writing to a File:

    with open("output.txt", "w") as file: file.write("Hello, File!")
  4. Appending to a File:

    with open("output.txt", "a") as file: file.write("\nAppended text.")

Working with Binary Files

  1. Writing Binary Data:

    with open("binary_file.bin", "wb") as file: file.write(b"Binary Data")
  2. Reading Binary Data:

    with open("binary_file.bin", "rb") as file: data = file.read() print(data)

Advanced File Handling

  1. Reading File Line-by-Line:

    with open("example.txt", "r") as file: for line in file: print(line.strip()) # Removes newline characters
  2. Using os and pathlib for File Operations:

    • Example:
      import os if os.path.exists("example.txt"): os.remove("example.txt")

Standard Error Output

Python provides the sys.stderr object for sending error messages to the console.

import sys sys.stderr.write("This is an error message.\n")

Redirecting I/O

  1. Redirecting Input:

    with open("input.txt", "r") as file: sys.stdin = file user_input = input() # Reads from file instead of console
  2. Redirecting Output:

    with open("output.txt", "w") as file: sys.stdout = file print("This will go to the file instead of the console.")

Working with JSON and CSV Files

  1. JSON:

    import json # Writing JSON data = {"name": "Alice", "age": 25} with open("data.json", "w") as file: json.dump(data, file) # Reading JSON with open("data.json", "r") as file: data = json.load(file) print(data)
  2. CSV:

    import csv # Writing CSV with open("data.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["Name", "Age"]) writer.writerow(["Alice", 25]) # Reading CSV with open("data.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row)

Conclusion

Python simplifies I/O operations with easy-to-use functions like input(), print(), and the powerful open() for file handling. Advanced modules like os, json, and csv make working with files and structured data even more efficient.

Comments

  1. وفجاه عيني وقعت عليها ايدي جت ع وسطها شفايفي جت ع حرفها كانت احلي كومبايه شاي شربتها ونا بقرا هذا المحتوي الجبار جميل اخي استمر

    ReplyDelete

Post a Comment

Popular posts from this blog