0
点赞
收藏
分享

微信扫一扫

Python 打开和读取文件的方式

这是一篇介绍python读取文件的几种方式文章

一、打开和读取文件的方式

"""
打开文件的方式可以使用
f=open(path,'r')
f.close()
来打开和关闭文件
或者使用 with open(file, mode, encoding) as f:
使用with不用再手动关闭文件
"""

# 使用read()读取
# 一次性读取
# 把文件全部内容一次性读到一个字符串中。就是一坨的那种,如果把ff用循环读取的方式输出,会是一个一个字符,因为ff是字符串
path = r'E:\江上渔者.txt'
with open(file=path, mode='r', encoding='utf-8') as fd:
    content = fd.read()
print(content)
print('--------------------------------------------------')

# 使用readlines()读取
# 一次性读取
# 这个函数将文件所用内容以行为区分读到一个列表中 ,列表中的每一个元素是一行
with open(file=path, mode='r', encoding='utf-8') as fd:
    content_list = fd.readlines()
    print(content_list)
for line in content_list:
    print(line, end='')
print('\n', '--------------------------------------------------')

# 使用readline()读取,每次只读一行,因此要重复读取
# 逐行读取
# 当没有足够内存可以一次读取整个文件时,且文件有分行的时候,可使用 readline()。
with open(file=path, mode='r', encoding='utf-8') as fd:
    content = fd.readline()
    while content:
        print(content, end='')
        content = fd.readline()

print('\n', '--------------------------------------------------')
# 当文件较大,且没有分行的时候,可以使用read(size)依次读取
with open(file=path, mode='r', encoding='utf-8') as fd:
    content = fd.read(1024)
    while True:
        print(content, end='')
        content = fd.read(1024)
        if not content:
            break
print(content)
print('--------------------------------------------------')
# 最为推荐的方式为使用with迭代器
with open(file=path, mode='r', encoding='utf-8') as fd:
    for line in fd:
        print(line, end='')

二、访问模式

访问模式.jpg

举报

相关推荐

0 条评论