Python3 读写文件

2020-01-29  本文已影响0人  tafanfly

读写是Python中常见的操作, 通过读写请求操作系统打开文件对象,然后读取数据或者写入数据。

1. 读文件

with open('file.txt', 'r+') as f:
    print(f.read())

#testing
2020-01-25Python 3.9.0a3 now available for testing
2020-01-17Start using 2FA and API tokens on PyPI
2020-01-07Python Software Foundation Fellow Members for Q4 2019

read() 是一次性读取文件的全部内容,即一次性把文件加载到内存, 如果文件很大, 超出内存范围,会报错MemoryError。 所以需要读取指定字节数。下面只是用了小文件举例。

DATA_SIZE=20
with open('file.txt', 'r+') as f:
    while True:
        block = f.read(DATA_SIZE)
        if block:
            print(block)
        else:
            break

#testing
2020-01-25Python 3.9
.0a3 now available f
or testing
2020-01-1
7Start using 2FA and
 API tokens on PyPI

2020-01-07Python Sof
tware Foundation Fel
low Members for Q4 2
019
with open('file.txt', 'r+') as f:
    while True:
        line = f.readline()
        if line:
            print(line)
        else:
            break
#testing
2020-01-25Python 3.9.0a3 now available for testing

2020-01-17Start using 2FA and API tokens on PyPI

2020-01-07Python Software Foundation Fellow Members for Q4 2019
with open('file.txt', 'r+') as f:
    print(f.readlines())
#testing
['2020-01-25Python 3.9.0a3 now available for testing\n', '2020-01-17Start using 2FA and API tokens on PyPI\n', '2020-01-07Python Software Foundation Fellow Members for Q4 2019']
with open('file.txt', 'r+') as f:
    for line in f:
        print(line)
# testing
2020-01-25Python 3.9.0a3 now available for testing

2020-01-17Start using 2FA and API tokens on PyPI

2020-01-07Python Software Foundation Fellow Members for Q4 2019

总结:
f.read()f.readlines() 方法都是一次性读取文件全部内容,操作比较方便,但是对于大文件,会出现内存溢出等问题,所以需要使用f.read(size)文件对象f的方法。

2. 快速无误的读取大文件

with open('file.txt', 'r+') as f:
    for line in f:
        print(line)
def read_big_file(filename, size=4096):
    with open(filename, 'r+') as f:
        while True:
            block = f.read(size)
            if block:
                yield block
            else:
                break

for block in read_big_file('file.txt'):
    print(block)
# testing
2020-01-25Python 3.9.0a3 now available for testing
2020-01-17Start using 2FA and API tokens on PyPI
2020-01-07Python Software Foundation Fellow Members for Q4 2019

3. 写文件

with open('file.txt', 'w+') as f:
    f.write('Hello!\n')
# testing
cat file.txt 
Hello!
with open('file.txt', 'w+') as f:
    f.writelines(['Hello\n', 'World\n'])
# testing
cat file.txt 
Hello
World

总结:
写文件操作是比较简单的,但是一定要记住,写入文件后要关闭文件

写文件时,操作系统为提高效率,往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。

一旦程序崩溃, 可能会导致中途写入的数据丢失, 所以推荐使用with open函数。

上一篇 下一篇

猜你喜欢

热点阅读