【课程8.1】 文件对象声明及基本操作
另一种数据格式:文件/文档
1.本地文件的界定:指向一个本地存储的文件,是一个链接或者一个映射
path1 = 'C:/Users/Hjx/Desktop/text.txt' # 单个反斜杠:/
path2 = 'C:\\Users\\Hjx\\Desktop\\text.txt' # 两个斜杠:\\(第一个\是转义符)
path3 = r'C:\Users\Hjx\Desktop\text.txt' # r用于防止字符转义
# 路径书写格式
print(path1)
print(path2)
print(path3)
-----------------------------------------------------------------------
C:/Users/Hjx/Desktop/text.txt
C:\Users\Hjx\Desktop\text.txt
C:\Users\Hjx\Desktop\text.txt
2.读取文件:open语句
f = open(path2, 'r')
print(type(f))
print(f)
print(f.read())
print('读取完毕')
# open('路径', '模式', enconding = '编码' )
# 模式:r:读取文件,默认;w:写入;rw:读取+写入;a:追加
# 简答的读取方法:.read() → 读取后,光标将会留在读取末尾
print(f.read())
print('读取为空')
# 运行第一次.read()之后,光标位于末尾,再次读取输出为空
f.seek(0)
print(f.read())
print('第二次读取')
# 所以现在用 f.seek(0) 来移动光标
f.close()
# print(f.read()) # 关闭后无法读取
# 关闭文件链接 f.close(),养成一个好习惯
-----------------------------------------------------------------------
<class '_io.TextIOWrapper'>
<_io.TextIOWrapper name='C:\\Users\\Hjx\\Desktop\\text.txt' mode='r' encoding='cp936'>
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
读取完毕
读取为空
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
第二次读取