Python学习Day09(文件操作)

文件常用操作:

打开文件:(Open)

格式:

f = open(文件路径,操作符,encoding=编码)

文件路径:包括相对路径和绝对路径,如果不写的话,系统会默认当前文件夹的目录

操作符:包括 r(读取read),w(写入write)、a(追加append)、wb(以二进制流写入)、rb(以二进制流读取)……

encoding:这个是设置字符编码,一般用utf8

文件写:write

with open(r'./user.txt','w',encoding='utf-8') as file:

         file.write("hello.this is some data.")
#说明:
#如果这个文本文件是不存在的,系统会创建一个新的文本文件,如果存在的话,w操作符写入的数据会把原来的内#容覆盖
#r 是表示原始字符串
#./ 是表示当前目录,../ 是表示上一级目录

文件读:read

with open(r'./user.txt','r',encoding='utf-8') as file:

        fil_content=file.read() print(fil_content)
print(s)  #读取完成了之后,文件读取指针就在末尾,下面索性就关闭再重新打开
#输出结果:hello.this is some data.

文件写追加:a

with open(r'./user.txt','a',encoding='utf-8') as file:

         file.writelines(["小白教程 1n", "小白教程 2","小白教程3"])

writelines() 方法用于向文件中写入一序列的字符串

with open(r'./user.txt','w',encoding='utf-8') as file:

        file.writelines(["小白教程 1n", "小白教程 2"])

readlines:按行读

with open(r'./user.txt','r',encoding='utf-8') as file:

        fil_content=file.readlines() print(fil_content) #['小白教程 1n小白教程 2小白教程 1n小白教程 2小白教程3']

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值