IO编程
1. 文件读写
练习:请将本地一个文本文件读为一个str并打印出来:
>>> with open('C:\\Users\\Administrator\\Desktop\\ss\\test.txt', 'r') as f:
... f.read()
...
'hello, world!'
2. 操作文件和目录
- 利用os模块编写一个能实现
dir -l
输出的程序。
from datetime import datetime
import os
pwd = os.path.abspath('.')
print(' Size Last Modified Name')
print('------------------------------------------------------------')
for f in os.listdir(pwd):
fsize = os.path.getsize(f)
mtime = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d %H:%M')
flag = '/' if os.path.isdir(f) else ''
print('%10d %s %s%s' % (fsize, mtime, f, flag))
输出结果:
Size Last Modified Name
------------------------------------------------------------
741 2020-12-07 17:12 1-数据类型.py
86 2020-12-15 17:10 2.py
427 2020-12-16 08:59 3-函数参数.py
409 2020-12-16 14:31 4-迭代.py
386 2021-03-01 10:10 hello.py
379 2020-12-16 14:37 test.py
- 编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
def search_file(path, str): # 传入当前的绝对路径以及指定字符串
# 首先先找到当前目录下的所有文件
for file in os.listdir(path): # os.listdir(path) 是当前这个path路径下的所有文件的列表
this_path = os.path.join(path, file) # 用户拼接用户设置查询路径和查询路径的所有文件
if os.path.isfile(this_path): # 判断这个路径对应的是目录还是文件,是文件就走下去
if str in file:
print(this_path)
else: # 不是就再次执行这个函数,递归下去
search_file(this_path, str) # 使用路径继续递归下去
if __name__ == "__main__":
search_file(os.path.abspath('C:\\Users\\Administrator\\Desktop\\ss'), ".txt")
输出结果:
C:\Users\Administrator\Desktop\ss\aa\11.o\111.txt
C:\Users\Administrator\Desktop\ss\aa\test1.txt
C:\Users\Administrator\Desktop\ss\aa\test2.txt
C:\Users\Administrator\Desktop\ss\aa\test3.txt
C:\Users\Administrator\Desktop\ss\aa\test4.txt
C:\Users\Administrator\Desktop\ss\aa\test5.txt
C:\Users\Administrator\Desktop\ss\test.txt
3. 序列化
通过对比可知,ensure_ascii
为True时中文是乱码,为False时中文正常显示。