目錄
一、內存交互
1.1 變量與數據結構
1.2 對象的創建和方法調用
1.3 操作內存中的數據
二、磁盤交互
2.1?文件讀寫
2.2 操作系統相關的文件操作
2.3?讀寫 JSON 文件
2.4?讀寫 CSV 文件
一、內存交互
內存交互:主要涉及變量、數據結構、對象的創建與操作,以及使用 StringIO
和 BytesIO
等類在內存中操作數據。
1.1 變量與數據結構
- 變量的賦值和使用都在內存中進行。
- 數據結構如列表(list)、字典(dict)、集合(set)、元組(tuple)等都是在內存中操作的。
# 變量和數據結構在內存中操作
a = 10
b = [1, 2, 3, 4, 5]
c = {"name": "Alice", "age": 30}
1.2 對象的創建和方法調用
- Python 中對象的創建、方法調用等操作都是在內存中進行的。
class MyClass:def __init__(self, value):self.value = valuedef increment(self):self.value += 1obj = MyClass(5)
obj.increment()
1.3 操作內存中的數據
- 使用
io.StringIO
和io.BytesIO
類,可以在內存中操作字符串和字節流。
from io import StringIO, BytesIO# 使用 StringIO 在內存中操作字符串
mem_str = StringIO()
mem_str.write("Hello, world!")
mem_str.seek(0)
print(mem_str.read())# 使用 BytesIO 在內存中操作字節流
mem_bytes = BytesIO()
mem_bytes.write(b"Hello, world!")
mem_bytes.seek(0)
print(mem_bytes.read())
二、磁盤交互
磁盤交互:主要涉及文件讀寫、操作系統文件操作(如創建、刪除、重命名文件和目錄)、讀寫 JSON 文件和 CSV 文件等。
2.1?文件讀寫
- 使用內置的
open()
函數讀寫文件,這是最常見的磁盤交互方式。
# 寫入文件
with open('example.txt', 'w') as file:file.write("Hello, world!")# 讀取文件
with open('example.txt', 'r') as file:content = file.read()print(content)
2.2 操作系統相關的文件操作
- 使用
os
模塊進行文件和目錄的創建、刪除、重命名等操作,這些操作都會與磁盤交互。
import os# 創建目錄
os.mkdir('new_directory')# 重命名文件
os.rename('example.txt', 'new_example.txt')# 刪除文件
os.remove('new_example.txt')# 刪除目錄
os.rmdir('new_directory')
2.3?讀寫 JSON 文件
- 使用
json
模塊將 Python 對象序列化為 JSON 格式并寫入文件,或從文件中讀取 JSON 格式的數據并反序列化為 Python 對象。
import jsondata = {"name": "Alice", "age": 30}# 寫入 JSON 文件
with open('data.json', 'w') as file:json.dump(data, file)# 讀取 JSON 文件
with open('data.json', 'r') as file:loaded_data = json.load(file)print(loaded_data)
2.4?讀寫 CSV 文件
- 使用
csv
模塊讀寫 CSV 文件,與磁盤進行交互。
import csv# 寫入 CSV 文件
with open('data.csv', 'w', newline='') as file:writer = csv.writer(file)writer.writerow(['Name', 'Age'])writer.writerow(['Alice', 30])writer.writerow(['Bob', 25])# 讀取 CSV 文件
with open('data.csv', 'r') as file:reader = csv.reader(file)for row in reader:print(row)