Python之文件操作

2019-07-22  本文已影响0人  EchoPython

说到文件操作,我们就想到了读写操作,在python中对于文件操作就是读和写,访问文件的模式有两种,文本模式和二级制模式。

1.文件打开

# 现创建一个hello.txt文件,然后加入内容hello world
f = open(file='./hello.txt')
result = f.read()
print(result )  #输出: hello world
f.close()

如果你依然在编程的世界里迷茫,
不知道自己的未来规划,
对python感兴趣,
这里推荐一下我的学习交流圈QQ群:895 797 751,
里面都是学习python的,

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

2.mode模式参数常用值有哪些

3.文件读取

f = open(file='./hello.txt',mode='w')
result = f.read()
print(result) # hello world

f.write('a')  # 如果写入则会报错,因为此时是只读模式
#
result1 = f.read(3)  # 表示文件读三个字节,不给值表示直接读到EOF
print(result1) # hel

f.close() # 读取完文件一定要关闭

4.文件写入

f = open(file='./hello.txt', mode='w')
f.write('a')
f.read() # 此时读就会报错
f.close()

# x是只写,文件不存在,创建文件,以只写方式打开
f = open('./test.txt', 'x')
# f.read() # 此时读会报错
f.write('a')
f.close()

# a只写,文件存在,追加内容,文件不存在,只写,追加内容
f = open('./test1.txt', 'a')
# f.read() # 此时读会报错
f.write('aaa')
f.close()

5.文件指针

f = open('hello.txt', 'r+')
print(f.tell()) # 文件的起始位置 0
print(f.read()) # 读文件所有的内容
print(f.tell()) # EOF,也就是最后一个字符是几
print(f.seek(3)) # 偏移两个字节
print(f.read())
f.close()

f = open('test.txt', 'rb+')
print(f.tell()) # 文件的起始位置0
print(f.read()) # 读文件所有的内容
print(f.tell()) # EOF,也就是最后一个字符
print(f.seek(2)) # 偏移两个字节
print(f.read())

f.write(b'ni hao')
f.seek(2,2) # 二级制模式下,seek(offset, whence=0) 可以给whence传递1, 2 或 0, 0表示文件从头开始, 1表示从当前位置开始,2表示从文件末尾EOF开始
f.seek(1,1)
f.write(b'ni hao')
f.flush() # 将缓存刷新到文件
f.write(b'ni hao')
f.close() # 文件句柄关闭的时候,会将缓存刷新到文件

6.文件行读取

import io
f = open('hello.txt', 'r+')
print(io.DEFAULT_BUFFER_SIZE) # 8192
print(f.readline(), '第一行')  # 读取一行
print(f.readline(), '第二行')
print(f.readlines())          # 读取所有行,且返回列表

7.open 文件上下文管理器

with open('test.txt',mode='w') as f:
    f.write('nihao')
    
如果你依然在编程的世界里迷茫,
不知道自己的未来规划,
对python感兴趣,
这里推荐一下我的学习交流圈QQ群:895 797 751,
里面都是学习python的,
上一篇 下一篇

猜你喜欢

热点阅读