文件读写基础

如何读取整个文件内容?

with open(filename, "r", encoding="utf-8") as file:

content = file.read() # 读取整个文件内容

如何写入文件(不存在则创建)?

with open(filename, "w", encoding="utf-8") as file:

file.write(content) # 将内容写入文件,直接覆盖

如何在文件末尾追加内容?

with open(filename, "a", encoding="utf-8") as file:

file.write(content) # 在文件末尾追加内容

如何按行读取为列表?

with open(filename, "r", encoding="utf-8") as file:

lines = file.readlines() # 读取所有行,返回列表

return [line.strip() for line in lines]

文件与目录操作

如何检查文件是否存在并获取大小?

if os.path.exists(filename): # 检查文件是否存在

size = os.path.getsize(filename) # 获取文件大小(字节)

如何重命名文件?

os.rename(old_name, new_name)

如何创建多级目录?

os.makedirs("new_folder/new_child_folder", exist_ok=True)

如何复制/移动/删除文件与目录?

复制文件:

shutil.copy("new_folder/new_child_folder/test.txt", "test_copy.txt")

移动文件:

shutil.move("new_folder/new_child_folder/test.txt", "test_move.txt")

删除文件:

os.remove("test_move.txt")

删除目录:

shutil.rmtree("new_folder")

权限与类型

Linux权限字符串如何解读?

示例:-rw-r--r--

第1位:类型(- 普通;d 目录;l 软链接 ...)

第2-4位:所有者(User) 权限 rwx

第5-7位:同组(Group) 权限 rwx

第8-10位:其他人(Others) 权限 rwx

数字权限对照表?

0 --- 无;1 --x 执行;2 -w- 写;3 -wx 写+执行;

4 r-- 读;5 r-x 读+执行;6 rw- 读+写;7 rwx 读+写+执行

如何判断是文件还是目录?

os.path.isfile('file.txt')

os.path.isdir('folder')

如何获取与修改权限?

获取:

file_stat = os.stat("快速开始.md")

permissions = stat.filemode(file_stat.st_mode)

修改:

os.chmod('file.txt', 0o755) # rwxr-x-rx

文件查找与通配

如何递归查找所有.txt文件?

all_files = glob.glob('**/*.txt', recursive=True)

压缩与解压

如何创建/解压ZIP文件?

创建:

with zipfile.ZipFile('archive.zip', 'w') as zipf:

zipf.write('file1.txt')

zipf.write('file2.txt')

解压:

with zipfile.ZipFile('archive.zip', 'r') as zipf:

zipf.extractall('extracted/')

如何创建/解压TAR文件?

创建:

with tarfile.open('archive.tar.gz', 'w:gz') as tar:

tar.add('folder/', arcname='folder')

解压:

with tarfile.open('archive.tar.gz', 'r:gz') as tar:

tar.extractall('extracted/')

系统与硬件信息

如何获取系统与Python信息?

print(f"操作系统: {platform.system()}")

print(f"系统版本: {platform.release()}")

print(f"架构: {platform.machine()}")

print(f"处理器: {platform.processor()}")

print(f"系统Python版本: {platform.python_version()}")

print(f"系统主机名: {platform.node()}")

如何获取内存与磁盘信息?

内存:

memory = psutil.virtual_memory()

print(f"总内存: {memory.total / 1024 / 1024 / 1024:.2f} GB")

print(f"可用内存: {memory.available / 1024 / 1024 / 1024:.2f} GB")

print(f"内存使用率: {memory.percent}%")

磁盘:

disk = psutil.disk_usage('/')

print(f"磁盘总容量: {disk.total / 1024 / 1024 / 1024:.2f} GB")

print(f"磁盘使用率: {disk.percent}%")

如何查看网络信息?

network = psutil.net_if_addrs()

print(f"网络信息: {network['en0'][0]}")

定时任务

如何使用schedule实现定时任务?

# 每10秒执行一次

schedule.every(10).seconds.do(job)


# 每天执行

schedule.every().day.at("10:30").do(job)


# 每周执行

schedule.every().monday.do(job)


# 运行调度器

while True:

schedule.run_pending()

time.sleep(1)

数据存储

如何保存/读取TXT?

保存:

with open('data.txt', 'w', encoding='utf-8') as f:

f.write('数据内容

')

读取:

with open('data.txt', 'r', encoding='utf-8') as f:

content = f.read()

如何保存/读取JSON?

保存:

data = {'name': '张三', 'age': 25}

with open('data.json', 'w', encoding='utf-8') as f:

json.dump(data, f, ensure_ascii=False, indent=2)

读取:

with open('data.json', 'r', encoding='utf-8') as f:

data = json.load(f)

如何保存/读取Excel?

保存:

data = {

'姓名': ['张三', '李四', '王五'],

'年龄': [25, 30, 35],

'城市': ['北京', '上海', '广州']

}

df = pd.DataFrame(data)

df.to_excel('data.xlsx', index=False)

读取:

df = pd.read_excel('data.xlsx')

print(df)