Python 之 os、open、json、pickle 模块的“疯狂”探险记

1.open函数的使用
Python 中的 open() 函数是处理文件的标准方法。它允许你打开一个文件,并对其进行读取、写入或追加操作

open(file,mode,encoding)函数的格式:

file:文件路径
mode:打开方式(
                读: r
                写: w   读完之后光标停留在最后读取的位置
                追加: a
                可读写    r+(文件不存在就报错)
                可读写    w+(文件不存在就创建,如果文件内有内容会覆盖)
                可读写    a+(光标默认停留在最后,不可直接读取到内容,使用seek(0)调整光标位置),无论光标在哪,默认在最后写入
                读取二进制  rb
                写二进制  wb
encoding:解码方式


 1.1 打开文件并读取内容:使用当你读写完文件后,需要关闭该文件,而with open 会自动帮你关闭文件。open 函数 需要你自己关闭文件。

f = open("./1.helloword.py", mode="w", encoding="utf8")
s.readable()
# 读取文件
content = s.read()
print(content)

cont = s.readline()
print(cont)

# 关闭文件
s.close()

第二种方法:

# 打开文件进行读取
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)


其他的常见方法:

readable():是否可读,返回True or False
read():读取整个文件,返回字符串
readline():只读取一行,返回字符串
readlines():逐行读取整个文件,将每行的字符串放进一个列表,返回列表


 1.2 写入文件:
覆盖原文件内容,若没有文件则创建

# 打开文件进行写入
with open('output.txt', 'w') as f:
    f.write('Hello, World!\n')
    f.write('This is a new line.')


其他的常见方法:

writeable:是否可写,返回True or False
write:每次写入一行,但是不会自动换行,没有文件会自动创建,写入的数据必须是字符串
writelines:每次写入多条数据,参数是iterable类型数据,也不会自动换行


1.3 追加内容到文件末尾: 

# 打开文件进行追加
with open('example.txt', 'a') as f:
    f.write('\nThis is appended content.')


 2. 数据序列化:Json与Pickle
在 Python 中,json 和 pickle 是两种常用的数据序列化和反序列化模块,用于将数据转换为文件中可存储或传输的格式。

2.1 Json 序列化与反序列化

import json
 
# 将 Python 对象转换为 JSON 字符串并写入文件
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
    json.dump(data, f)
 
# 从 JSON 文件中读取数据并解析为 Python 对象
with open('data.json', 'r') as f:
    loaded_data = json.load(f)
    print(loaded_data)


2.2 Pickle 序列化与反序列化:

import pickle
 
# 将 Python 对象序列化并写入文件
data = {'name': 'Bob', 'age': 25, 'city': 'San Francisco'}
with open('data.pkl', 'wb') as f:
    pickle.dump(data, f)
 
# 从 Pickle 文件中读取数据并反序列化为 Python 对象
with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)
    print(loaded_data)


3. 文件和目录管理:os 模块
Python 的 os 模块提供了许多与操作系统交互和文件系统操作相关的函数。

3.1 文件和目录操作示例:

import os
 
# 获取当前工作目录
print(os.getcwd())
 
# 创建目录
os.mkdir('my_directory')
 
# 列出目录中的文件
print(os.listdir('.'))
 
# 删除文件
os.remove('unnecessary_file.txt')
 
# 删除目录
os.rmdir('my_directory')

3.2 路径操作与文件属性:

# 检查路径是否存在
print(os.path.exists('data.json'))
 
# 获取文件大小
print(os.path.getsize('data.json'))
 
# 分离文件名与路径
print(os.path.split('/path/to/file.txt'))
 
# 检查是否是文件或目录
print(os.path.isfile('data.json'))
print(os.path.isdir('my_directory'))


结论
本文介绍了 Python 中常用的文件操作方法 open() 函数,以及数据序列化和反序列化的 json 和 pickle 模块,最后探讨了 os 模块在文件系统操作中的应用。通过这些内容,你可以更好地理解和利用 Python 进行文件管理和数据处理的技巧。

希望本文能帮助你在 Python 开发中更加熟练地处理文件和操作系统相关任务。如果有任何疑问或建议,请留言讨论!

相关推荐

  1. Python实现奇怪疯狂按键需求

    2024-07-23 05:46:04       29 阅读
  2. -探究 OpenApi 加密方式

    2024-07-23 05:46:04       57 阅读
  3. 【随手pythonnonlocal关键字

    2024-07-23 05:46:04       43 阅读
  4. Python模块logging

    2024-07-23 05:46:04       89 阅读
  5. 疯狂程序员重头暴学英语语法宝典!!!

    2024-07-23 05:46:04       43 阅读
  6. Python时间和日期:探索datetime模块

    2024-07-23 05:46:04       68 阅读
  7. Python上下文管理:深入探索contextlib模块

    2024-07-23 05:46:04       21 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-23 05:46:04       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-23 05:46:04       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-23 05:46:04       45 阅读
  4. Python语言-面向对象

    2024-07-23 05:46:04       55 阅读

热门阅读

  1. 微信小程序面试题汇总

    2024-07-23 05:46:04       14 阅读
  2. Ubuntu22.04重置root密码

    2024-07-23 05:46:04       16 阅读
  3. 手写简易版Spring IOC容器05【学习】

    2024-07-23 05:46:04       14 阅读
  4. 速盾:cdn技术实现原理是什么?

    2024-07-23 05:46:04       17 阅读
  5. Windows通过命令查看mac : getmac

    2024-07-23 05:46:04       18 阅读
  6. CentOS搭建 Mono 开发环境

    2024-07-23 05:46:04       13 阅读
  7. MVC(Model-View-Controller)架构简介

    2024-07-23 05:46:04       17 阅读
  8. 科普文:重读并翻译分布式计算经典文论-MapReduce

    2024-07-23 05:46:04       13 阅读
  9. Apache Commons技术详解

    2024-07-23 05:46:04       18 阅读
  10. mqtt.fx 下载 安装 配置

    2024-07-23 05:46:04       18 阅读