Reading and writing data in files in Python: Basic methods and examples of use

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Data input and output (I/O) are fundamental operations in programming that allow programs to interact with the user and external information sources. Python provides a powerful and intuitive set of tools for working with data, which we will explore in detail in this guide.

Data output in Python: print() function

The print() function is the main tool for displaying information in Python. It provides many features for formatted data output to the console or to files.

Basics of working with print()

The simplest use of the print() function is to output text or variable values:

print("Hello, world!") # Outputs a text string
x = 10
print("The value of x is:", x) # Outputs the text and the value of the variable

Formatting output in Python

Python offers several ways to format strings for beautiful data output:

name = "Anna"
age = 25
salary = 50000.50

# Method .format()
print("Name: {}, Age: {}, Salary: {:.2f}".format(name, age, salary))

# F-strings (recommended method)
print(f"Name: {name}, Age: {age}, Salary: {salary:.2f}")

# The old way of formatting
print("Name: %s, Age: %d, Salary: %.2f" % (name, age, salary))

Parameters of the print() function

The print() function has several useful parameters:

The sep parameter defines the separator between the elements.:

print("apple", "banana", "orange", sep=", ") # Outputs: apple, banana, orange
print("2024", "01", "15", sep="-") # Outputs: 2024-01-15

The end parameter defines the line ending character.:

print("Download", end="")
for i in range(3):
print(".", end="")
print("Done!")  # Outputs: Loading... It's done!

The file parameter allows you to send the output to a file.:

with open("log.txt", "w", encoding="utf-8") as file:
    print("Information saved to a file", file=file)

Data entry in Python: input() function

The input() function allows you to receive data from the user interactively. It always returns a string that needs to be converted to other data types, if necessary.

Basics of working with input()

# Simple input without invitation
name = input()
print(f"Hello, {name}!")

# Prompt input
age = input("Enter your age: ")
print(f"You are {age} years old")

Data type conversion

Since input() always returns a string, it is necessary to convert the data to the desired type.:

# Convert to integer
age = int(input("Enter your age:"))

# Conversion to a floating point number
height = float(input("Enter your height in meters: "))

# Processing a list of values
numbers = input("Enter numbers separated by a space:").split()
numbers = [int(num) for num in numbers]

Input error handling

It is important to provide for the processing of incorrect input:

while True:
    try:
        age = int(input("Enter your age: "))
if age < 0:
print("Age cannot be negative")
continue
        break
    except ValueError:
        print("Please enter the correct number")

print(f"Your age: {age}")

Validation of user input

def get_valid_email():
    while True:
        email = input("Enter email: ")
        if "@" in email and "." in email:
            return email
        print("Incorrect email format")

email = get_valid_email()
print(f"Your email: {email}")

Working with files in Python

Python provides powerful tools for working with files, allowing you to read and write data in various formats.

 

Writing data to a file

# Writing text to a file
with open("output.txt", "w", encoding="utf-8") as file:
    file.write("Hello, world!\n")
file.write("This is the second line\n")

# Writing a list of lines
lines = ["First line", "Second line", "Third line"]
with open("lines.txt", "w", encoding="utf-8") as file:
    file.writelines(line + "\n" for line in lines)

Reading data from a file

# Reading the entire file
with open("input.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)

# Reading the file line by line
with open("input.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())  # strip() deletes newline characters

# Reading a file into a list
with open("input.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()
    print(lines)

File opening modes

mode
  Description
"r" Read (default)
"w" Recording (overwrites the file)
"a" Adding to the end of the file
"r+" Reading and writing
"b" Binary mode (added to the main mode)

Working with CSV files

import csv

# Writing a CSV file
data = [
    ["Name", "Age", "City"],
    [Alexey, 30, Moscow],
    ["Maria", 25, "Saint Petersburg"]
]

with open("data.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# Reading a CSV file
with open("data.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Advanced I/O techniques

Formatting numbers and dates

from datetime import datetime

# Formatting numbers
price = 1234.5678
print(f"Price: {price:.2f} rub.") # Price: 1234.57 rub.
print(f"Price: {price:,.2f} rub.") # Price: 1,234.57 rub.

# Formatting dates
now = datetime.now()
print(f"Current date: {now:%d.%m.%Y}")
print(f"Current time: {now:%H:%M:%S}")

Working with JSON files

import json

# Saving data in JSON
data = {
    "name": "Ivan",
"age": 30,
"city": "Moscow",
"hobbies": ["programming", "reading", "sports"]
}

with open("data.json", "w", encoding="utf-8") as file:
    json.dump(data, file, ensure_ascii=False, indent=2)

# Reading data from JSON
with open("data.json", "r", encoding="utf-8") as file:
    loaded_data = json.load(file)
    print(loaded_data)

Creating interactive programs

def calculator():
    print("A simple calculator")
print("Available operations: +, -, *, /")
    
    while True:
        try:
            num1 = float(input("Enter the first number: "))
operator = input("Enter the operation (+, -, *, /): ")
            num2 = float(input("Enter the second number: "))
            
            if operator == "+":
                result = num1 + num2
            elif operator == "-":
                result = num1 - num2
            elif operator == "*":
                result = num1 * num2
            elif operator == "/":
if num2 == 0:
print("Division by zero is impossible!")
continue
                result = num1 / num2
            else:
print("Unknown operation")
continue
            
            print(f"Result: {result}")
            
            if input("Continue? (y/n): ").lower() != 'y':
                break
                
        except ValueError:
            print("Error: enter the correct number")

calculator()

Best practices for working with I/O in Python

1. Always use the context manager with

# Correct
with open("file.txt", "r") as file:
    content = file.read()

# Wrong
file = open("file.txt ", "r")
content = file.read()
file.close() # You can forget to close the file

2. Specify the encoding when working with files

with open("file.txt", "r", encoding="utf-8") as file:
    content = file.read()

3. Handle exceptions

try:
    with open("file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("No permission to read the file")

4. Validate user input

def get_positive_number(prompt):
    while True:
        try:
            num = float(input(prompt))
if num > 0:
return num
print("The number must be positive")
except ValueError:
            print("Enter the correct number")

Conclusion

Python data input and output provide programmers with powerful tools for creating interactive applications and processing information. Understanding the functions print() and input(), as well as working with files, is the basis for creating functional programs.

Basic principles of working with I/O in Python:

  • Use f-strings to format the output
  • Always handle exceptions when working with files
  • Validate user input
  • Use context managers to work with files
  • Specify the encoding when working with text files

This knowledge will help you create reliable and user-friendly programs that interact effectively with users and process data in various formats.

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base