目录
文件内建函数 | 功能 |
---|---|
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
"""