DEV Community

niuniu
niuniu

Posted on

Quick Tip: Python File Operations

Quick Tip

Python file operations:

# Read file
with open('file.txt', 'r') as f:
    content = f.read()

# Write file
with open('file.txt', 'w') as f:
    f.write("Hello, World!")

# Append to file
with open('file.txt', 'a') as f:
    f.write("New line")

# Read lines
with open('file.txt', 'r') as f:
    lines = f.readlines()

# JSON file
import json
with open('data.json', 'r') as f:
    data = json.load(f)

with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)
Enter fullscreen mode Exit fullscreen mode

Powered by MonkeyCode: https://monkeycode-ai.net/

python #coding #tips

Top comments (0)