当前位置: 首页 > 工具软件 > Python ispy > 使用案例 >

Python3学习18--IO编程

段干开宇
2023-12-01

本系列博文基于廖雪峰老师的官网Python教程,笔者在大学期间已经阅读过廖老师的Python教程,教程相当不错,官网链接: 廖雪峰官方网站.请需要系统学习Python的小伙伴到廖老师官网学习,笔者的编程环境是Anaconda+Pycharm,Python版本:Python3.



1.文件读写

# 读写文件:请求操作系统打开一个文件对象,通过操作系统提供的接口
# 从这个文件对象中读取数据(读文件),把数据写入这个文件对象(写文件);
# 使用Python内置的open()函数打开文件对象,传入文件名和标示符;
f = open("hello.py", "r")

# 调用read()方法一次读取文件的全部内容
f.read()

# 调用close()方法关闭文件
f.close()
# 保证无论是否出错,都能正确关闭文件
try:
    f = open("hello.py", "r")
    print(f.read())
finally:
    if f:
        f.close()
       
# 结果输出:
# print("Hello.I am Willard.")
# print("Welcome to FUXI Technology.")
# 使用with语句自动调用close()方法
with open("hello.py", "r") as f:
    print(f.read())

# 结果输出:
# print("Hello.I am Willard.")
# print("Welcome to FUXI Technology.")
# read()一次性读取文件的全部内容
# read(size):每次最多读取size个字节的内容
# 调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list
f = open("hello.py", "r")

for line in f.readlines():
    print(line.strip())

f.close()

# 结果输出:
# print("Hello.I am Willard.")
# print("Welcome to FUXI Technology.")
# 读取二进制文件
f = open("J20.jpg", "rb")

f.read()
f.close()
----------------------------------------------------------------------
# 字符编码
f = open("gbk_coding.txt", "r", encoding = "utf-8", errors = "ignore")
f.read()
f.close()
----------------------------------------------------------------------
# 写文件
f = open("welcome.py", "w")
f.write("Welcome to FUXI Technology.")
f.write("My name is Willard.")
f.close()
----------------------------------------------------------------------
# 使用with写入文件
with open("welcome.py", "w") as f:
    f.write("Welcome to FUXI Technology.\n")
    f.write("I am Willard.")

2.StringIO

# StringIO:在内存中读写str

# 把str写入String
from io import StringIO

f = StringIO()
f.write("Hello Python.\n")
f.write("I am Willard.\n")
f.write("Welcome to FUXI Technology.\n")

print(f.getvalue())    # getvalue()方法用于获得写入后的str

# 结果输出:
# Hello Python.
# I am Willard.
# Welcome to FUXI Technology.
# 读取StringIO
from io import StringIO

f = StringIO("Hello Willard.\nWelcome to FUXI Technology.")

while True:
    s = f.readline()
    if s == "":
        break
    print(s.strip())

# 结果输出:
# Hello Willard.
# Welcome to FUXI Technology.

3.BytesIO

# BytesIO:在内存中读写bytes

# 写入bytes
from io import BytesIO

f = BytesIO()
f.write("中国".encode("utf-8"))
print(f.getvalue())

# 结果输出:
# b'\xe4\xb8\xad\xe5\x9b\xbd'
# 读取bytes
# 读取bytes
from io import BytesIO

f = BytesIO(b'\xe4\xb8\xad\xe5\x9b\xbd')
bytes_read = f.read()
print("b'\\xe4\\xb8\\xad\\xe5\\x9b\\xbd'翻译过来:", bytes_read.decode())

# 结果输出:
# b'\xe4\xb8\xad\xe5\x9b\xbd'翻译过来: 中国

4.操作文件和目录

import os

print("OS type is:", os.name)
print("If posix,os's type is Linux、Unix or Mac OS X.")
print("If nt,os's type is Windows.")
print("------------------------------------------------")

# 获取某个环境变量的值
print(os.environ.get("PATH"))
# 结果输出:
OS type is: nt
If posix,os's type is Linux、Unix or Mac OS X.
If nt,os's type is Windows.
------------------------------------------------
C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;
# 操作文件和目录
import os

# 查看当前目录的绝对路径
print("当前目录的绝对路径:\n", os.path.abspath("."))
print("----------------------------------------------------------------")

# 在某个目录下创建一个新目录,先把这个目录完整路径表示
os.path.join("C:/Users/Administrator/廖雪峰Python3学习笔记", "Willard")

# 创建目录
os.mkdir("C:/Users/Administrator/廖雪峰Python3学习笔记/Willard")

# 删除一个目录
os.rmdir("C:/Users/Administrator/廖雪峰Python3学习笔记/Willard")

# 拆分路径
print("拆分路径:\n", os.path.split("C:/Users/Administrator/廖雪峰Python3学习笔记/hello.txt"))
print("----------------------------------------------------------------")

# 获取文件扩展名
print("获取文件扩展名:\n", os.path.splitext("C:/Users/Administrator/廖雪峰Python3学习笔记/hello.py"))

# 对文件重命名
os.rename("hello.txt", "hello.cpp")

# 删除文件
os.remove("hello.cpp")
# 结果输出:
当前目录的绝对路径:
 C:\Users\Administrator\廖雪峰Python3学习笔记
----------------------------------------------------------------
拆分路径:
 ('C:/Users/Administrator/廖雪峰Python3学习笔记', 'hello.txt')
----------------------------------------------------------------
获取文件扩展名:
 ('C:/Users/Administrator/廖雪峰Python3学习笔记/hello', '.py')
# 过滤文件
import os

isdir = [x for x in os.listdir(".") if os.path.isdir(x)]
print("列出本目录下所有文件夹:\n", isdir)
print("----------------------------------------------------------------")

# 列出所有.py文件
ispy = [x for x in os.listdir(".") if os.path.isfile(x) and os.path.splitext(x)[1] == ".py"]
print("列出本目录下所有.py文件:\n", ispy)
print("----------------------------------------------------------------")

# 列出所有.js文件
isjs = [x for x in os.listdir(".") if os.path.isfile(x) and os.path.splitext(x)[1] == ".js"]
print("列出本目录下所有.js文件:\n", isjs)
# 结果输出:
列出本目录下所有文件夹:
 ['.ipynb_checkpoints', '__pycache__']
----------------------------------------------------------------
列出本目录下所有.py文件:
 ['hello.py', 'mydict.py', 'mydict2.py', 'mydict_test.py', 'welcome.py']
----------------------------------------------------------------
列出本目录下所有.js文件:
 ['control.js', 'order.js']

5.序列化

# dumps和loads
# 序列化但不写入文件
import pickle

pickle_list = [1, 2, 3, 4, 5]
pickle_tuple = (1, 2, 3, 4, 5)
pickle_dict = {"name" : "Willard", "age" : 18}

print("使用dumps进行序列化:")
print("-----------------------------------------------------")

res_list = pickle.dumps(pickle_list)
res_tuple = pickle.dumps(pickle_tuple)
res_dict = pickle.dumps(pickle_dict)

print("res_list:\n", res_list)
print("res_tuple:\n", res_tuple)
print("res_dict:\n", res_dict)
print("-----------------------------------------------------")
print("-----------------------------------------------------")

# 反序列化
print("使用loads进行反序列化:")
print("-----------------------------------------------------")

print("res_list:\n", pickle.loads(res_list))
print("res_tuple:\n", pickle.loads(res_tuple))
print("res_dict:\n", pickle.loads(res_dict))
# 结果输出:
使用dumps进行序列化:
-----------------------------------------------------
res_list:
 b'\x80\x03]q\x00(K\x01K\x02K\x03K\x04K\x05e.'
res_tuple:
 b'\x80\x03(K\x01K\x02K\x03K\x04K\x05tq\x00.'
res_dict:
 b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x07\x00\x00\x00Willardq\x02X\x03\x00\x00\x00ageq\x03K\x12u.'
-----------------------------------------------------
-----------------------------------------------------
使用loads进行反序列化:
-----------------------------------------------------
res_list:
 [1, 2, 3, 4, 5]
res_tuple:
 (1, 2, 3, 4, 5)
res_dict:
 {'name': 'Willard', 'age': 18}
# dump和load
# 序列化并写入文件
import pickle

pickle_list = [1, 2, 3, 4, 5]
pickle_tuple = (1, 2, 3, 4, 5)
pickle_dict = {"name" : "Willard", "age" : 18}

# 序列化并写入文件
with open("f1","wb") as f:
    pickle.dump(pickle_list,f, True)
    pickle.dump(pickle_tuple,f, True)
    pickle.dump(pickle_dict,f, True)

print("使用dump进行序列化:\n")
with open("f1", "r") as f:
    print(f.read())

print("-------------------------------------------------")

# load反序列化
print("使用load进行反序列化:\n")
with open("f1", "rb") as f:
    res1 = pickle.load(f)
    res2 = pickle.load(f)
    res3 = pickle.load(f)
    
    print(res1)
    print(res2)
    print(res3)
# 结果输出:
使用dump进行序列化:

]q(KKKKKe.(KKKKKtq.}q(XnameqXWillardqXageqKu.
-------------------------------------------------
使用load进行反序列化:

[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)
{'name': 'Willard', 'age': 18}

6.JSON

"""
JSON:表示为一个字符串,可以被所有语言读取,方便地存储到磁盘或通过网络传输;
JSON:是标准格式,比XML更快,可以直接在WEB页面读取,十分方便;

JSON和Python内置的数据类型对应:
JSON类型                  Python类型
{}                        dict
[]                        list
"string"                  str
1234.56                   int或float
true/false                True/False
null                      None
"""
# 把Python对象变成一个JSON
import json

dict_eg = dict(name = "Willard", age = 25, salary = 10000)
print("json.dumps:", json.dumps(dict_eg))    # dumps()方法返回一个str,内容为标准的JSON

# 把JSON反序列化为Python对象,用loads()方法
json_str = '{"name": "Willard", "age": 25, "salary": 10000}'
print("json_str:", json.loads(json_str))

# 结果输出:
# json.dumps: {"name": "Willard", "age": 25, "salary": 10000}
# json_str: {'name': 'Willard', 'age': 25, 'salary': 10000}
 类似资料: