文件的操作 —— Python

1、打开文件:open()函数

1)函数定义:
def open(file, mode=‘r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True):

file:需要操作的额文件名(字符串形式)
mode:对文件的操作类型
字符的意思:
‘r’ open for reading (default)(只读模式打开(默认方式))
‘w’ open for writing, truncating the file first(写入模式打开)
‘x’ create a new file and open it for writing(创建一个文件并以写入模式打开)
‘a’ open for writing, appending to the end of the file if it exists(写入模式打开,如果文件存在则在其末尾追加)
‘b’ binary mode(以二进制模式打开)
‘t’ text mode (default)(以文本文件模式打开(默认方式))
‘+’ open a disk file for updating (reading and writing)(打开一个磁盘文件用于更新(读写))
‘U’ universal newline mode (deprecated)

2)使用举例:

#打开文本文件
f = open("a.txt", 'w', encoding="utf-8")

#以二进制模式打开媒体文件
f = open("a.mp3", 'rb')

2、关闭文件:close()方法

```
f.close()
```

3、读取文件

1)read()方法
定义: def read(self, n=None):
read()方法参数为空,则一次性将整个文件读取到内存中,若传入参数,如read(6),则只读取文件中的前6个字符

#打开文件
f = open("a.txt", 'r', encoding="utf-8")		#打开文件,当文件中有中文时,要写encoding=“utf-8”(对于二进制文件不能写该项)
#读取文件并打印
print(f.read())											#读取文件并打印
f.close()													#关闭文件

运行结果:
hello python!
hello world!
好样的!

:文件a.txt内容如下,下同

hello python!
hello world!
好样的!

2)readline()方法
定义:def readline(self, limit=-1):
每次只读取文件中的一行,若readline()没有参数,则读取整行,若有参数,如readline(6),则读取该行的前6个字符

f = open("a.txt", 'r', encoding="utf-8")
print(f.readline())
f.close()
运行结果:
hello python!

f = open("a.txt", 'r', encoding="utf-8")
print(f.readline())
print(f.readline())
f.close()
运行结果:
hello python!

hello world!

3)readlines()方法
定义:def readlines(self, hint=-1):
读取整个文件,返回一个列表,将文件中的每一行作为一个字符串元素

f = open("a.txt", 'r', encoding="utf-8")
print(f.readlines())
f.close()
运行结果:
['hello python!\n', 'hello world!\n', '好样的!']

4、写文件:write()方法

定义:def write(self, s):
将字符串s写入到文件中,返回写入的字符数

f = open("a.txt", 'r', encoding="utf-8")
fb = open("b.txt", "w", encoding="utf-8")

fb.write(f.read())
f.close()
fb.close()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值