第十集:文件操作

'''
文件操作:
针对磁盘中的文件的读写. 文件的io/ 输入input和输出 output
写入文件的操作:
打开文件:1.open open(文件的路径,打开的方式,[字符集])从当前目录开始计算
文件路径:相对路径: ./demo.txt 当前目前的demo.txt
../demo.txt代表当前目录上一级目录中的demo.txt
demo.txt 具体文件没有任何表示 默认为当前目录和./demo.txt一个写法
绝对路径:c://user
2.打开方式 w r x a b
w :write 写入
1.如果不存在则创建
2.如果存在则打开并清空文件
3.打开后 文件指针在最开始
r: r模式 read 读取模式
如果文件不存在直接报错,文件存在则打开 指针在最前面
参数可选参数encoding 设置文件的字符集 y一般encoding = utf-8
x:x or 异或模式
1.文件不存在 ,则创建这个文件
2.文件已存在则报错 防止覆盖
3.也是在最前面
a:append追加模式
1.文件不存在 则创建文件
2.文件存在则打开,不会清空文件
扩展模式:b
b 模式 bytes 二进制
+ 模式 plus 增强模式 (可读可写 )

文件操作模式的组合:
w r a x
wb rb ab xb
w+ r+ a+ x+
wb+ rb+ ab+ xb+

写入内容write
关闭:close
读取文件的操作:
打开文件open
读取内容read
关闭close
'''
# 1.打开文件
filepath = 'D:\Autotest\cyz\day5'
# file = open('demo')
file = open('demo','w',encoding='UTF-8')
print(file,type(file))


# 第二步写入
file.write('你好\n我的')


# 第三步,关闭
file.close()


# 2.读取文件

fp = open('./demo','r',encoding='UTF-8')
# 异或模式 打开一个已经存在的会报错
# fp = open('demo','x',encoding='UTF-8')
oo = fp.readlines()
for i in oo:
print(i.strip())
fp.close()
# 结果
# <_io.TextIOWrapper name='demo' mode='w' encoding='UTF-8'> <class '_io.TextIOWrapper'>
# 你好
# 我的
posted @ 2022-02-27 17:16  冬天里的狐狸  阅读(50)  评论(0编辑  收藏  举报