Python读写文件操作

简介: Python读写文件操作

一、文件编码

1.1 什么是编码?

不变吗就是一种规则集合,记录了内容和二进制相互转换的逻辑,常用的有UTF-5、GBK等编码

1.2 为什么需要编码?

计算机只认识二进制的0和1,所以需要将内容翻译成二进制才能保存在计算机中。同时也需要编码,反向翻译回原始文件内容。

二、文件的读取

读取大致分为三步:打开文件、读取文件、关闭文件

2.1 open函数
2.2 read函数

read(nbytes),从文件中读取nbytes字节的数据,如果没写参数nbytes,默认读取文件的全部内容

2.3 readlines函数

按行读取文件内容,将每行数据保存到列表容器,用返回值接收。

2.4 readline函数

读取文件的一行。

2.5 close 函数

关闭文件

2.6 with open 函数

with open(“E:/Program/Python/test.txt”, “r”, encoding=“UTF-8”) as f, 可以避免忘记关闭文件而导致的异常。

import time # 导入sleep需要的包
file = open("E:/Program/Python/test.txt", "r", encoding="UTF-8")
print(type(file))
# 1.read方法
print(file.read(10)) # 读取10个字节
print(file.read())   # 读取全部内容
# 2.readlines方法
file_list = file.readlines()
print(file_list)
print(type(file_list))
# 3. readline
print(file.readline())
# 4.循环读取每一行
for item in file.readlines():
    print(item)
time.sleep(10)
# 5.关闭文件
file.close()
# 6.with open,可以避免忘记关闭文件而导致的异常
with open("E:/Program/Python/test.txt", "r", encoding="UTF-8") as f:
    for line in f:
        print(line)

三、文件的写入

直接调用write,内容并未真正写入到文件,只是写在了磁盘的缓冲区,当调用flush时才会真正落盘。为什么要调用flush才落盘呢?这样是为了避免频繁的刷盘导致性能下降,只有在特定时候才会刷盘。

import time
file = open("E:/Program/Python/python.txt", "w", encoding="UTF-8")
file.write("hello, this is lwang.")
file.write("hello, this is lwang.")
file.write("hello, this is lwang.")
file.write("hello, this is lwang.")
# time.sleep(100000)
file.flush()
# time.sleep(100000)
file.close()  # close内置flush功能
# 追加写测试
file2 = open("E:/Program/Python/python2.txt", "a", encoding="UTF-8")
file2.write("hello,world!")
file2.write("\nhere is lwang.")
file2.flush()
file2.close()


推荐一个零声学院免费教程,个人觉得老师讲得不错,分享给大家:[Linux,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,TCP/IP,协程,DPDK等技术内容,点击立即学习:

相关文章
|
1天前
|
Python
【Python操作基础】——帮助文档
【Python操作基础】——帮助文档
|
1天前
|
Python
【Python操作基础】——包
【Python操作基础】——包
|
1天前
|
Python
【Python操作基础】——函数
【Python操作基础】——函数
|
1天前
|
Python
【Python操作基础】——字典,迭代器和生成器
【Python操作基础】——字典,迭代器和生成器
|
1天前
|
Python
【Python操作基础】——集合
【Python操作基础】——集合
|
1天前
|
索引 Python
【Python操作基础】——序列
【Python操作基础】——序列
|
1天前
|
Python
【Python操作基础】——字符串
【Python操作基础】——字符串
|
1天前
|
Python
【Python操作基础】——元组
【Python操作基础】——元组
|
1天前
|
Python
【Python操作基础】——列表操作
【Python操作基础】——列表操作
|
1天前
|
Python
【Python操作基础】——while语句用法和pass语句
【Python操作基础】——while语句用法和pass语句