Python 文件输入输出

1. 打开文件

1.1 open() 方法

Python open() 方法用于打开一个文件,并返回文件对象。在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

open(file, mode='r')

完整的语法格式为:

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

参数说明:

  • file: 必需,文件路径(相对或者绝对路径)
  • mode: 可选,文件打开模式
  • buffering: 设置缓冲,可用内存代替硬盘,使程序更快

参数解释详见:Python3 File(文件) 方法

1.2 文件模式

模式 描述
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
b 二进制模式。
+ 打开一个文件进行更新(可读可写)。

参数解释详见:Python3 File(文件) 方法

2. 基本的文件方法

2.1 读和写

file 对象使用 open 函数来创建,使用write和read方法来写入和读取数据。

f = open('somefile.txt','w')
f.write('Hello,')
f.write('wordl!')
f.close()

f = open('somefile.txt','r')
print(f.read(5))
print(f.read())
f.close()

输出:

Hello
,wordl!

注意:换行写入需要在字符后面加上\n

f = open('somefile.txt','w')
f.write('01234567890123456789\n')
f.write('Hello,world!\n')
f.close()

f = open('somefile.txt','r')
print(f.readline())
f.close()

2.2 随机访问

seek() 方法用于移动文件读取指针到指定位置。seek() 方法语法如下:

fileObject.seek(offset[, whence])

参数

  • offset – 开始的偏移量,也就是代表需要移动偏移的字节数
  • whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
f = open('somefile.txt','w')
f.write('01234567890123456789')
f.seek(5)
f.write('Hello,world!')
f.close()

f = open('somefile.txt','r')
print(f.read())
f.close()

输出:

01234Hello,world!789

tell() 方法返回文件的当前位置,即文件指针当前位置。tell() 方法语法如下:

fileObject.tell()
f = open('somefile.txt','r')
print(f.read(3))
print(f.read(2))
print(f.tell())
f.close()

输出:

012
34
5

2.3 读取行

readline() 方法用于从文件读取整行,包括 “\n” 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 “\n” 字符。readline() 方法语法如下:

fileObject.readline(size)

参数
size – 从文件中读取的字节数。
返回值
返回从字符串中读取的字节。

line = f.readline()

readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,该列表可以由 Python 的 for… in … 结构进行处理。 如果碰到结束符 EOF 则返回空字符串。readlines() 方法语法如下:

fileObject.readlines( );

参数
无。
返回值
返回列表,包含所有的行。

2.5 对文件内容迭代

2.5.1 按字节处理

方法1:

def process(string):
    print('Proecss: ',string)

f = open('somefile.txt','w')
f.write('First line\n')
f.write('Second line\n')
f.write('Third line\n')
f.close()

f = open('somefile.txt','r')
char = f.read(1)
while char:
    process(char)
    char = f.read(1)
f.close()

方法2:

f = open('somefile.txt','r')
while True:
    char = f.read(1)
    if not char:
        break
    process(char)
f.close()

2.5.2 按行处理

f = open('somefile.txt','r')
while True:
    line = f.readline()
    if not line:
        break
    process(line)
f.close()

2.5.3 读取所有内容

如果文件不是很大,可以使用read或者readlines全部读取。文件很大时候,可以使用while和readline来代替。

f = open('somefile.txt','r')
for char in f.read():
    process(char)
f.close()
f = open('somefile.txt','r')
for line in f.readlines():
    process(line)
f.close()

2.5.4 使用fileinput进行迭代

fileinput模块包含了打开文件的函数。

import fileinput
for line in fileinput.input('somefile.txt'):
    process(line)

输出:

Proecss:  First line
Proecss:  Second line
Proecss:  Third line

2.5.5 文件迭代器

超酷的方法,好像readlines方法没有必要存在了。
方法1:

f = open('somefile.txt','r')
for line in f:
    process(line)
f.close()

方法2:

for line in open('somefile.txt','r'):
    process(line)

虽然应该有file对象,用于关闭打开的文件,但是,只要没有向文件中写入操作,不关闭也是可以的。

方法3:

lines = list(open('somefile.txt','r'))
print(lines)

将文件迭代器转换为字符串列表,达到和使用readlines一样的效果。

2.6 来自ChatGPT的例子

例子1:

	filename = 'test.txt'
    fid = open(filename)

    if fid == -1:
        print(f"The file '{filename}' does not exist.")
        return

    bulletinas = []
    i = 0
    while not fid.eof():
        current_line = fid.readline()
        print(current_line)

例子2:

	filename = 'test.txt'
    bulletinas = []
    with open(filename) as f:
        for current_line in f:
        print(current_line)        

参考:ChatGPT https://openai.com/

3. 二进制文件读写

Python 读写文件的二进制数据比 C/C++ 语言复杂得多。主要差别在于需要进行 bytes 类型和其它基础数据类型(比如 int/float)的转换。
详见:
[1] python处理二进制文件(.bin)
[2] Python 读写文件的二进制数据

猜你喜欢

转载自blog.csdn.net/wokaowokaowokao12345/article/details/128801327