Show List

Python Input and Output (I/O) operations

In Python, Input and Output (I/O) operations refer to the process of reading data from an input source and writing data to an output source. Here are some common I/O operations in Python, along with examples.

  • Reading Input from the Keyboard: The input function is used to read input from the keyboard. It returns the input as a string, which can then be converted to other data types as needed.

Here's an example:

python
Copy code
name = input("Enter your name: ") print("Hello, ", name)
  • Writing Output to the Screen: The print function is used to write output to the screen. You can pass one or more expressions as arguments to the print function, and it will convert them to strings and display them on the screen.

Here's an example:

makefile
Copy code
x = 10 y = 20 print("The sum of", x, "and", y, "is", x + y)
  • Reading from a File: To read data from a file, you need to open the file in reading mode and use the read or readline method to read its contents.

Here's an example that reads the contents of a file and displays them on the screen:

scss
Copy code
file = open("file.txt", "r") content = file.read() print(content) file.close()
  • Writing to a File: To write data to a file, you need to open the file in write mode and use the write method to write its contents. If the file does not exist, it will be created. If it exists, its contents will be overwritten.

Here's an example that writes some data to a file:

lua
Copy code
file = open("file.txt", "w") file.write("Hello, World!") file.close()

These are some of the basic I/O operations in Python. Note that it's important to close the file after you're done reading or writing its contents, to ensure that the changes are saved and the resources are freed.


    Leave a Comment


  • captcha text