python读写文件模板——精讲

读写模式

要了解文件读写模式,需要了解几种模式的区别

r :   读取文件,若文件不存在则会报错
w :   写入文件,若文件不存在则会先创建再写入,会覆盖原文件
a :   写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾
rb, wb:  分别与r,w类似,但是用于读写二进制文件
r+ :   可读、可写,文件不存在也会报错,写操作时会覆盖
w+ :   可读,可写,文件不存在先创建,会覆盖
a+ :  可读、可写,文件不存在先创建,不会覆盖,追加在末尾

'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) 已废弃

open()函数完整参数

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
参考博客

读文件

python常用的读取文件函数有三种read()、readline()、readlines()

read(可选:size) 一次性读全部内容

一次性读取文本中全部的内容,以字符串的形式返回结果
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

with open("test.txt", "r") as f:  # 打开文件
    data = f.read()  # 读取文件
    print(data)

readline() 读取一行内容

只读取文本第一行的内容,以字符串的形式返回结果
f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.

with open("test.txt", "r") as f:
    data = f.readline()
    print(data)

readlines() 读取所有内容,返回列表

读取文本所有内容,并且以列表的格式返回结果,一般配合for循环使用
If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().

with open("test.txt", "r") as f:
    data = f.readlines()
    print(data)

readlines会读到换行符,可用如下方法去除

with open("test.txt", "r") as f:
    for line in f.readlines():
        line = line.strip('\n')  #去掉列表中每一个元素的换行符
        print(line)

从file中读取每行 等同于 readlines()的功能

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

with open("test.txt", "r") as f:
    for line in f:
        print(line, end = '')

写文件

python常用的读取文件函数有三种write()、writelines()、flush()

write(str) 将字符串的内容写入文件,返回写入的字符数

file.write(str)的参数是一个字符串,就是你要写入文件的内容
其他类型的对象在编写之前需要转换为字符串(文本模式)或字节对象(二进制模式)

with open("test.txt", "w") as f:
    int num = f.write('This is a test\n')  # num == 15

writelines(sequence)函数

file.writelines(sequence)的参数是序列,比如列表、字符串序列,它会迭代帮你写入文件
使用 writelines() 函数向文件中写入多行数据时,不会自动给各行添加换行符

# 实现复制一个文本文件a.txt -> b.txt
f = open('a.txt', 'r')
n = open('b.txt','w+')
n.writelines(f.readlines())
n.close()
f.close()

f.seek(offset, whence) 改变文件对象的位置,类比于unix接口lseek

offset:开始的偏移量,也就是代表需要移动偏移的字节数

whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。

f = open('workfile', 'rb+')
f.write(b'0123456789abcdef')

f.seek(5)      # Go to the 6th byte in the file

f.read(1)

f.seek(-3, 2)  # Go to the 3rd byte before the end

f.read(1)

手动调用flush() 一般open后调用close即可把缓冲区的数据写入文件(即磁盘)中

如果向文件写入数据后,不想马上关闭文件,也可以调用文件对象提供的 flush() 函数,它可以实现将缓冲区的数据写入文件中

f = open("a.txt", 'w')
f.write("写入一行新数据")
f.flush()  # 一般open后调用close即可把缓冲区的数据写入文件(即磁盘)中

参考文章

python官方文档
txt、csv、xlsx等文件读写
python读取、写入txt文本内容
Python write()和writelines()
Python文件操作(I/O)

posted @ 2022-09-19 17:46  胖白白  阅读(197)  评论(0编辑  收藏  举报