Last modified: Feb 19, 2026 By Alexander Williams
Python Input Output Guide: Read Write Files
Python input and output are fundamental skills. They let your programs interact with users and data. This guide covers everything you need to know.
You will learn about user input, file operations, and data formatting. These concepts are crucial for building useful applications.
Getting User Input with input()
The input() function is your main tool. It pauses the program and waits for the user to type. The typed text is returned as a string.
This simple interaction is the start of dynamic programs. Always remember that input() always returns a string.
# Basic example of the input() function
user_name = input("Please enter your name: ")
print(f"Hello, {user_name}!")
Please enter your name: Alice
Hello, Alice!
Converting Input to Other Data Types
Since input() gives you a string, you often need to convert it. Use functions like int() or float() for numbers.
This step is vital for calculations. Forgetting to convert is a common beginner mistake.
# Converting string input to an integer
age_string = input("Enter your age: ")
age_integer = int(age_string) # Convert the string to an integer
print(f"In 10 years, you will be {age_integer + 10} years old.")
Enter your age: 25
In 10 years, you will be 35 years old.
Output with the print() Function
The print() function displays information. You can print strings, variables, and the results of expressions. It's how your program talks to the world.
You can control the output with parameters like `sep` and `end`. This makes your output clean and readable.
# Demonstrating print() with different arguments
name = "Bob"
score = 95
print(name, "scored", score, "points.") # Multiple items
print(name, "scored", score, "points.", sep=" - ", end="!\n") # Custom separator and end
Bob scored 95 points.
Bob - scored - 95 - points.!
Formatted Strings (f-strings)
Formatted strings, or f-strings, are the best way to mix variables and text. They make your code much easier to read and write.
Place an 'f' before the string and put variables in curly braces `{}`. Python will replace them with their values.
# Using f-strings for clean output formatting
item = "book"
price = 19.99
quantity = 3
total = price * quantity
# The f-string neatly embeds the variables
receipt = f"You bought {quantity} {item}s for ${price:.2f} each. Total: ${total:.2f}"
print(receipt)
You bought 3 books for $19.99 each. Total: $59.97
Reading from Files
Reading files lets your program use saved data. The process is simple: open the file, read its content, and close it.
Using a `with` statement is the safest method. It automatically closes the file for you, even if an error occurs.
# Reading the entire content of a file
with open('notes.txt', 'r') as file: # 'r' mode is for reading
content = file.read() # Reads the whole file into a string
print("File content:")
print(content)
File content:
This is line one.
This is line two.
Writing to Files
Writing to files saves data from your program. You can create new files or overwrite existing ones. Use the `'w'` mode for writing.
Be careful! Opening a file in `'w'` mode will erase its previous content. To add to a file, use the `'a'` mode for appending.
# Writing a list of items to a new file
shopping_list = ["Apples", "Bread", "Milk"]
with open('list.txt', 'w') as file: # 'w' mode creates/overwrites the file
for item in shopping_list:
file.write(item + "\n") # write() does not add newlines automatically
print("Shopping list written to 'list.txt'")
Shopping list written to 'list.txt'
After running, the file `list.txt` will contain each item on a new line.
Handling File Paths and Errors
Files might not exist, or paths could be wrong. Your program should handle these errors gracefully. This prevents crashes.
Use `try` and `except` blocks to manage these situations. It's a key part of writing robust and reliable code.
# Safely trying to open a file that may not exist
filename = 'missing_file.txt'
try:
with open(filename, 'r') as file:
data = file.read()
print("File read successfully.")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except IOError:
print(f"Error: Could not read the file '{filename}'.")
Error: The file 'missing_file.txt' was not found.
Working with CSV and JSON Data
Real-world data often comes in structured formats like CSV or JSON. Python has built-in modules to handle these easily.
Using the `csv` and `json` modules is much simpler than parsing the files yourself. They handle the tricky details.
# Example: Reading a simple JSON configuration file
import json
# Assume 'config.json' contains: {"language": "Python", "version": 3.9}
with open('config.json', 'r') as file:
settings = json.load(file) # Loads JSON data into a Python dictionary
print(f"Language: {settings['language']}")
print(f"Version: {settings['version']}")
Language: Python
Version: 3.9
Conclusion
Mastering Python input and output opens many doors. You can build interactive tools, process data files, and save results.
Start with input() and print(). Then move to file handling with `open()`. Always use `with` statements and handle errors.
Practice these concepts regularly. They form the foundation for almost every Python program you will write. Keep your code clean and your users informed.