python语法入门四
2019-10-13 本文已影响0人
是我真的是我
- 文件
- os + time模块
- pickle模块
- 异常
文件
f = open('C:\\Users\\DHW\\Desktop\\work.txt')
print(f.read())
# Python 文件I/O
#
# 本章只讲述所有基本的 ......(等全部文本内容)
f.close()
f = open('C:/Users/DHW/Desktop/work.txt')
print(f.read(8)) # 读取8个字符
# Python文件
print(f.tell()) # 该读取第几个字节
# 10
f.seek(0, 0)
print(f.tell())
# 0
for lines in f:
print(lines)
# (打印文本内容)
f.close()
f = open('C:\\Users\\DHW\\Desktop\\write.txt', 'w')
f.write('写入文件')
# (创建文件并写入)
os + time模块
import os
print(os.getcwd())
# E:\pycharm\project
os.chdir('E:/')
print(os.getcwd())
# E:\
print(os.listdir('E:/'))
# (列举出所有的文件名)
'''
os.mkdir('E:/pycharm/project/A')
# 创建一个目录
os.remove('E:/pycharm/project/A/t.txt')
# 删除文件
os.rmdir('E:/pycharm/project/A')
# 删除空目录
'''
'''
os.system('calc')
# 打开计算器
os.system('cmd')
# 打开cmd命令
'''
print(os.curdir)
# .(显示当前目录)
print(os.sep)
# \(显示系统特定路径分隔符)
print(os.path.basename('E:/A/B/t.txt'))
# t.txt(返回路径中的文件名)
print(os.path.dirname('E:/A/B/t.txt'))
# E:/A/B(返回路径中的路径名)
print(os.path.split('E:\\A\\B\\C.txt'))
# ('E:\\A\\B', 'C.txt')
print(os.path.splitext('E:\\A\\B\\C.txt'))
# ('E:\\A\\B\\C', '.txt')
import time
sec = os.path.getatime('C:/Users/DHW/Desktop/write.txt')
print(time.localtime(sec))
# time.struct_time(tm_year=2019, tm_mon=10, tm_mday=13, tm_hour=15, tm_min=47, tm_sec=5, tm_wday=6, tm_yday=286, tm_isdst=0)
# getatime返回最近访问时间、getctime返回创建时间、getmtime返回最新修改时间
print(t.localtime())
# time.struct_time(tm_year=2019, tm_mon=10, tm_mday=15, tm_hour=14, tm_min=7, tm_sec=47, tm_wday=1, tm_yday=288, tm_isdst=0)
print(t.localtime()[0])
# 2019
pickle模块
import pickle
'永久存储'
my_list = [12, 342, 32, 'aaa']
pickle_file = open('my_list.pkl', 'wb')
pickle.dump(my_list, pickle_file)
pickle_file.close()
'查看存储'
pickle_file = open('my_list.pkl', 'rb')
my_list2 = pickle.load(pickle_file)
print(my_list2)
pickle_file.close()
异常
try:
sum = 1 + '1'
f = open('wenjian.txt')
print(f)
except (OSError, TypeError) as reason:
print('出错了:' + str(reason))
except:
print('出错了')
finally:
print('后续操作')
raise TypeError('新类型异常')
# TypeError: 新类型异常
try:
# 此语句可自动关闭文件
with open('data.txt', 'r') as f:
for each_line in f:
print(each_line)
except OSError as reason:
print(str(reason))
else:
# 此语句在try没有异常时执行(while后也有同样功能)
print('没有异常')
finally:
f.close()