开放的编程资料库

当前位置:我爱分享网 > Python教程 > 正文

Python读取文件

Python读取文件教程展示了如何在Python中读取文件。我们展示了几个读取文本和二进制文件的示例。

如果我们要读取一个文件,我们需要先打开它。为此,Python具有内置的open函数。

Python打开函数

open函数用于在Python中打开文件。

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

file是要打开的文件的名称。mode指示文件将如何打开:读取、写入或追加。buffering是一个可选的整数,用于设置缓冲策略。encoding是用于解码或编码文件的编码名称。errors是一个可选字符串,指定如何处理编码和解码错误。newline控制换行符的行为。

文件模式是:

/表>

首先,我们处理文本文件。在本教程结束时,我们将使用一个二进制文件。

Lost Illusions
Beatrix
Honorine
The firm of Nucingen
Old Goriot
Colonel Chabert
Cousin Bette
Gobseck
César Birotteau
The Chouans

我们使用这个文件来阅读文本。

Python读取

read函数最多读取size个字符作为一个字符串。如果size参数为负数,则读取直到EOF。

#!/usr/bin/python

with open('works.txt', 'r') as f:

    contents = f.read()
    print(contents)

该示例读取整个文件并打印其内容。

with open('works.txt', 'r') as f:

我们以读取模式打开works.txt文件。由于我们没有指定二进制模式,文件以默认文本模式打开。它返回文件对象fwith语句通过封装常见的准备和清理任务来简化异常处理。它还会自动关闭打开的文件。

contents = f.read()

我们调用文件对象的read函数。由于我们没有指定任何参数,它会读取整个文件。

$ ./read_all.py 
Lost Illusions
Beatrix
Honorine
The firm of Nucingen
Old Goriot
Colonel Chabert
Cousin Bette
Gobseck
César Birotteau
The Chouans

Python读取字符

通过为read函数提供size参数,我们可以指定要读取的字符数。

#!/usr/bin/python

with open('works.txt', 'r') as f:

    data1 = f.read(4)
    print(data1)

    data2 = f.read(20)
    print(data2)

    data3 = f.read(10)
    print(data3)

在示例中,我们从文件中读取了4、20和10个字符。

$ ./read_characters.py 
Lost
    Illusions
Beatrix
H
onorine
Th

Python读取线

readline函数读取到换行符或EOF并返回一个字符串。如果流已经在EOF,则返回一个空字符串。如果指定了size参数,则最多读取size个字符。

#!/usr/bin/python

with open('works.txt', 'r') as f:

    line = f.readline()
    print(line.rstrip())

    line2 = f.readline()
    print(line2.rstrip())

    line3 = f.readline()
    print(line3.rstrip())

在示例中,我们从文件中读取了三行。rstrip函数从字符串中删除尾随的换行符。

$ ./read_line.py 
Lost Illusions
Beatrix
Honorine

Python阅读线

readlines函数从流中读取并返回行列表。

#!/usr/bin/python

with open('works.txt', 'r') as f:

    lines = f.readlines()

    print(lines)

    for line in lines:

        print(line.strip())

在示例中,我们使用readlines读取文件的内容。我们打印行列表,然后使用for语句遍历该列表。

$ ./read_lines.py 
['Lost Illusions\n', 'Beatrix\n', 'Honorine\n', 'The firm of Nucingen\n', 
'Old Goriot\n', 'Colonel Chabert\n', 'Cousin Bette\n', 'Gobseck\n', 
'César Birotteau\n', 'The Chouans\n']
Lost Illusions
Beatrix
Honorine
The firm of Nucingen
Old Goriot
Colonel Chabert
Cousin Bette
Gobseck
César Birotteau
The Chouans

Python读取文件

由于open函数返回的文件对象是可迭代的,我们可以将它直接传递给for语句。

#!/usr/bin/python

with open('works.txt', 'r') as f:

    for line in f:

        print(line.rstrip())

该示例遍历文件对象以打印文本文件的内容。

$ ./read_file.py 
Lost Illusions
Beatrix
Honorine
The firm of Nucingen
Old Goriot
Colonel Chabert
Cousin Bette
Gobseck
César Birotteau
The Chouans

搜索函数

seek函数将流位置更改为给定的字节偏移量。

offset值是相对于whence指示的位置进行解释的。whence的默认值为SEEK_SET

whence的值是:

  • SEEK_SET或0–流的开始(默认);offset应为零或正值
  • SEEK_CUR或1–当前流位置;offset可能是负数
  • SEEK_END或2-流的结尾;偏移量通常为负数
#!/usr/bin/python

with open('works.txt', 'r') as f:

    data1 = f.read(22)
    print(data1)

    f.seek(0, 0)

    data2 = f.read(22)
    print(data2)

在示例中,我们从文本流中读取了22个字符。然后我们将流位置设置回开头并再次读取22个字符。

$ ./seeking.py 
Lost Illusions
Beatrix
Lost Illusions
Beatrix

告诉函数

tell函数返回当前流位置。

#!/usr/bin/python

with open('works.txt', 'r') as f:

    print(f'The current file position is {f.tell()}')

    f.read(22)
    print(f'The current file position is {f.tell()}')

    f.seek(0, 0)
    print(f'The current file position is {f.tell()}')

我们使用readseek移动流位置,并使用tell打印它。

$ ./telling.py 
The current file position is 0
The current file position is 22
The current file position is 0

Python使用try/except/finally读取文件

with语句简化了我们读取文件时的工作。如果没有with,我们需要手动处理异常并关闭资源。

#!/usr/bin/python

f = None

try:

    f = open('works.txt', 'r')

    for line in f:
        print(line.rstrip())

except IOError as e:

    print(e)

finally:

    if f:
        f.close()

在示例中,我们使用tryexceptfinally关键字处理异常和资源释放。

Python读取二进制文件

在下面的例子中,我们读取了一个二进制文件。

#!/usr/bin/python

with open('web.png', 'rb') as f:

    hexdata = f.read().hex()

    n = 2
    data = [hexdata[i:i+n] for i in range(0, len(hexdata), n)]

    i = 0
    for e in data:

        print(e, end=' ')
        i += 1

        if i % 20 == 0:
            print()

    print()

该示例读取PNG文件。它将数据输出为十六进制值。

with open('web.png', 'rb') as f:

我们以读取和二进制模式打开PNG文件。

hexdata = f.read().hex()

我们读取所有数据并使用hex函数将其转换为十六进制值。

n = 2
data = [hexdata[i:i+n] for i in range(0, len(hexdata), n)]

我们将字符串分成两个字符的列表。

i = 0
for e in data:

    print(e, end=' ')
    i += 1

    if i % 20 == 0:
        print()

我们按列打印数据;列之间有一个空间。每行输出有20列。

$ ./read_binary.py 
89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 10 
00 00 00 10 08 06 00 00 00 1f f3 ff 61 00 00 03 2a 49 44 41 
54 78 01 75 53 43 98 23 69 18 ae eb 7a af eb 4a c6 b6 ed 38 
19 bb b5 6c db 66 55 45 dd 71 66 9f a4 ad 8a 9d b1 6d e3 fe 
ac 77 2f 63 bf 5b 55 a7 e1 e1 c7 a7 f7 33 01 e0 b5 43 6a 1a 
3e 27 e5 6d a9 62 b9 d6 39 4a a5 bd 3e 4a ad bb 22 56 d2 76 
...

这是一个示例输出。

在本教程中,我们展示了如何使用Python读取文件。

阅读Python教程或列出所有Python教程。

未经允许不得转载:我爱分享网 » Python读取文件

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏
模式 含义
‘r’ 打开阅读(默认)
‘w’ 打开写入,先截断文件
‘a’ 以写入方式打开,如果存在则追加到文件末尾
‘b’ 二进制模式
文本模式(默认)
‘+’ 更新(读写)
‘x’ 独占创建,文件存在失败