AITC Wiki

Python File I/O

Python 文件读写

Python File I/O

中文版:Python 文件读写

Reading from and writing to files, plus capturing user input through the console.

Writing and Reading Files

Python provides built-in functions for file operations. The with statement ensures files are properly closed after use.

# Write to a file
with open("file.txt", "w") as f:
    f.write("Hello, Python!")
 
# Read from a file
with open("file.txt", "r") as f:
    content = f.read()  # "Hello, Python!"
print(type(content), content)

User Input

The input() function pauses execution and reads a line of text from the user. The returned value is always a string.

nam = input('what is your name?')
print('Welcome', nam)  # Welcome <your input>

String Formatting

Python offers multiple ways to format output strings:

f-strings (Python 3.6+)

name = "Alice"
print(f"Hello, {name}!")  # Hello, Alice!
num = 2
print(f'Hello,{name}! num={num}#')

format() Method

print("Value: {}".format(10))  # Value: 10

Simple Concatenation

print('value:', name, '!', 'key:', num)  # value: Alice ! key: 2

Comments

# Single-line comment
 
"""
Multi-line comment
using triple quotes (also used for docstrings).
"""

Tip

In most IDEs, you can select lines of code and press Ctrl + / to toggle comments quickly.

Sources