Python中有用的工具(一)

本文介绍了Python中处理数据及文件的基本方法,包括使用pprint美化打印、利用pickle和cPickle进行对象序列化、通过json模块处理JSON数据、利用glob模块进行文件模式匹配以及使用shutil模块进行高级文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.pprint 模块:打印 Python 对象

pprint 是 pretty printer 的缩写,用来打印 Python 数据结构,与 print 相比,它打印出来的结构更加整齐,便于阅读。

>>> import pprint
>>> data = (
...     "this is a string",
...     [1, 2, 3, 4],
...     ("more tuples", 1.0, 2.3, 4.5),
...     "this is yet      another string"
...     )
>>> print (data) #使用普通的 print 函数
('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.3, 4.5), 'this is yet      another string')
>>> pprint.pprint(data) #使用 pprint 模块中的 pprint 函数
('this is a string',
 [1, 2, 3, 4],
 ('more tuples', 1.0, 2.3, 4.5),
 'this is yet      another string')

可以看到,这样打印出来的公式更加美观。

2.pickle, cPickle 模块:序列化 Python 对象

pickle 模块实现了一种算法,可以将任意一个 Python 对象转化为一系列的字节,也可以将这些字节重构为一个有相同特征的新对象。

由于字节可以被传输或者存储,因此 pickle 事实上实现了传递或者保存 Python 对象的功能。

cPickle 使用 C 而不是 Python 实现了相同的算法,因此速度上要比 pickle 快一些。但是它不允许用户从 pickle 派生子类。如果子类对你的使用来说无关紧要,那么 cPickle 是个更好的选择。

>>> try:
...     import cPickle as pickle
... except:
...     import pickle
...
>>> data = [{'a': 'A','b': 2,'c': 3.0}]
# 使用 pickle.dumps() 可以将一个对象转换为字符串(dump string)
>>> data_string = pickle.dumps(data)
>>> print("DATA:", data)
DATA: [{'b': 2, 'c': 3.0, 'a': 'A'}]
>>> print("PICKLE:", data_string)
PICKLE: b'\x80\x03]q\x00}q\x01(X\x01\x00\x00\x00bq\x02K\x02X\x01\x00\x00\x00cq\x03G@\x08\x00\x00\x00\x00\x00\x00X\x01\x00\x00\x00aq\x04X\x01\x00\x00\x00Aq\x05ua.'
# 虽然 pickle 编码的字符串并不一定可读,但是我们可以用 pickle.loads() 来从这个字符串中恢复原对象中的内容(load string)
>>> data_from_string = pickle.loads(data_string)
>>> print(data_from_string)
[{'b': 2, 'a': 'A', 'c': 3.0}]

3. json模块:处理JSON文件

JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。

JSON基础

JSON 的基础结构有两种:键值对 (name/value pairs) 和数组 (array)。

JSON 具有以下形式:

  • object-对象,用花括号表示,形式为(数据是无序的):
    { pair_1, pair_2, …, pair_n }
  • pair-键值对,形式为:
    string : value
  • array-数组,用中括号表示,形式为(数据是有序的):
    [value_1, value_2, …, value_n ]
  • value-值,可以是
    string 字符串
    number 数字
    object 对象
    array 数组
    true / false / null 特殊值
  • string 字符串

例子:

{
    "name": "echo",
    "age": 24,
    "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"],
    "ages for school": { 
        "primary school": 6,
        "middle school": 9,
        "high school": 15,
        "university": 18
    },
    "hobby": ["sports", "reading"],
    "married": false
}
JSON与Python的转换
>>> import json
>>> from pprint import pprint
>>> info_string = """
... {
...     "name": "echo",
...     "age": 24,
...     "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"],
...     "ages for school": {
...         "primary school": 6,
...         "middle school": 9,
...         "high school": 15,
...         "university": 18
...     },
...     "hobby": ["sports", "reading"],
...     "married": false
... }
... """
# 我们可以用json.loads()(load string)方法从字符串中读取JSON数据
>>> info = json.loads(in
in          info_string input(      int(
>>> info = json.loads(info_string)
>>> pprint(info)
{'age': 24,
 'ages for school': {'high school': 15,
                     'middle school': 9,
                     'primary school': 6,
                     'university': 18},
 'coding skills': ['python', 'matlab', 'java', 'c', 'c++', 'ruby', 'scala'],
 'hobby': ['sports', 'reading'],
 'married': False,
 'name': 'echo'}
 # 此时,我们将原来的JSON数据变成了一个python对象,在我们的例子中对象是个字典
>>> type(info)
<class 'dict'>
# 可以使用json.dumps()将一个Python对象变成JSON对象
>>> info_json = json.dumps(info)
>>> print(info_json)
{"age": 24, "hobby": ["sports", "reading"], "name": "echo", "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"], "married": false, "ages for school": {"high school": 15, "primary school": 6, "university": 18, "middle school": 9}}
#从中我们可以看到,生成的JSON字符串中,数组的元素顺序是不变的(始终是["python", "matlab", "java", "c", "c++", "ruby", "scala"]),而对象的元素顺序是不确定的。
生成和读取JSON文件

与pickle类似,我们可以直接从文件中读取JSON数据,也可以将对象保存为JSON格式。

  • json.dump(obj, file) 将对象保存为JSON格式的文件
  • json.load(file) 从JSON文件中读取数据
>>> with open("info.json", "w") as f:
...     json.dump(info, f)
...
# 可以查看info.json的内容
>>> with open("info.json") as f:
...     print(f.read())
...
{"age": 24, "hobby": ["sports", "reading"], "name": "echo", "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"], "married": false, "ages for school": {"high school": 15, "primary school": 6, "university": 18, "middle school": 9}}
# 从文件中读取数据
>>> with open("info.json") as f:
...     info_from_file = json.load(f)
...
>>> pprint(info_from_file)
{'age': 24,
 'ages for school': {'high school': 15,
                     'middle school': 9,
                     'primary school': 6,
                     'university': 18},
 'coding skills': ['python', 'matlab', 'java', 'c', 'c++', 'ruby', 'scala'],
 'hobby': ['sports', 'reading'],
 'married': False,
 'name': 'echo'}
 # 删除生成的文件
>>> import os
>>> os.remove("info.json")

4. glob模块:文件模式匹配

import glob
glob模块提供了方便的文件模式匹配方法

例如:找到所有以.py结尾的文件名:
glob.glob("*.py")

glob函数支持三种格式的语法:

  • *匹配单个或多个字符
  • ?匹配任意单个字符
  • []匹配指定范围内的字符,如:[0-9]匹配数字。

假设我们要匹配第09节所有的.ipynb文件:

glob.glob("../09*/*.ipynb")
# 输出
['../09. theano/09.05 configuration settings and compiling modes.ipynb',
 '../09. theano/09.03 gpu on windows.ipynb',
 '../09. theano/09.07 loop with scan.ipynb',
 '../09. theano/09.13 modern net on mnist.ipynb']

匹配数字开头的文件夹名:

glob.glob("../[0-9]*")
# 输出
['../04. scipy',
 '../02. python essentials',
 '../07. interfacing with other languages',
 '../11. useful tools']

5. shutil模块:高级文件操作

import shutil
import os
复制文件
with open("test.file", "w") as f:
    pass

print "test.file" in os.listdir(os.curdir)
# True

# shutil.copy(src, dst) 将源文件复制到目标地址:
shutil.copy("test.file", "test.copy.file")

print("test.file" in os.listdir(os.curdir)) # True
print("test.copy.file" in os.listdir(os.curdir)) # True

另外的一个函数 shutil.copyfile(src, dst) 与 shutil.copy 使用方法一致,不过只是简单复制文件的内容,并不会复制文件本身的读写可执行权限,而 shutil.copy 则是完全复制。

复制文件夹

将文件转移到test_dir文件夹:

os.renames("test.file", "test_dir/test.file")
os.renames("test.copy.file", "test_dir/test.copy.file")

# 使用 shutil.copytree 来复制文件夹:
shutil.copytree("test_dir/", "test_dir_copy/")

"test_dir_copy" in os.listdir(os.curdir) # True
删除非空文件夹

os.removedirs不能删除非空文件夹

使用shutil.rmtree来删除非空文件夹:
shutil.rmtree("test_dit_copy")

移动文件夹

shutil.move 可以整体移动文件夹,与 os.rename 功能差不多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值