Python:文件内建函数及常见操作

目录

1. open()

2. write()

3. read()

4.readline():读取一行

5.readlines():逐行读取

6.seek()


文件内建函数功能
open()打开文件
read()读取
readline()读取一行
readlines()逐行读取
seek()文件内移动
write()写入
close()

关闭文件

1. open()

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
pass

mode:默认'r',只读

'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. write()

eg:执行后生成一个name.txt的文件,被写入python

file = open('name.txt', 'w')
file.write('python')
file.close()


"""
txt执行结果:
python

"""

文件已存在,添加新内容,再次写入,mode = 'a'

file = open('name.txt', 'a')
file.write('\njava')
file.close()


"""
txt执行结果:
python
java
"""

3. read()

file = open('name.txt')
file.read()
# print(file.read())
file.close()

4.readline():读取一行

file = open('name.txt')
print(file.readline()) 
file.close()

# 执行结果 :python


"""
name.txt 文件内容:
python
java
go

"""

5.readlines():逐行读取

file = open('name.txt')
for line in file.readlines():
    print(line)
    print("--------")

"""
# 执行结果 :
python
--------
java
--------
go
--------
"""

"""
name.txt 文件内容:
python
java
go

"""

6.seek()

tell() 指针位置
file = open('name.txt')
print('当前指针位置%s' % file.tell())
print('当前读取到一个字符的内容%s' % file.read(1))
print('当前指针位置%s' % file.tell())
# 第一个参数代表偏移位置,第二个参数 0 表示从文件开头偏移 1 表示从当前位置偏移 2 从文件结尾位置偏移
file.seek(0, 0)
print('seek操作')
print('当前指针位置%s' % file.tell())
print('当前读取到一个字符的内容%s' % file.read(1))
print('当前指针位置%s' % file.tell())

"""
执行结果:
当前指针位置0
当前读取到一个字符的内容p
当前指针位置1
seek操作
当前指针位置0
当前读取到一个字符的内容p
当前指针位置1
"""

"""
name.txt 文件内容:
python
java
go

"""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值