python 2 教程
作者: CodeYang
文件读

文件读取的流程为:

打开文件-->读取数据-->关闭文件

文件打开函数为open,签名如下:

open(name, mode=None, buffering=None)

参数:

  • name: 文件路径
  • mode: 读取模式,常用的有 'r'-读,'w'-写,'b'-二进制,'a'-追加
  • buffering: 缓存大小

有以下两种方式读取文件:

1、try...finally

try:
    f=open("/root/data.txt","r")
    print(f.read())
finally:
    if f:
        f.close()

2、with.. as

with open("/root/data.txt","r") as f:
    print(f.read())

文件可以按以下几种方式读取:

1、按字符读取

with open("data.txt","r") as f:
    print(f.read())

print("----------------")
with open("data.txt","r") as f:
    print(f.read(2))
输出:
  • one
    two
    three
    four
    ----------------
    on

2、读取所有的行到list

print("----------------")
with open("data.txt","r") as f:
    list=f.readlines()
    print(list)
输出:
  • ['one\n', 'two\n', 'three\n', 'four']

3、逐行读取

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

输出:

  • one
标签: open、print、txt、读取、read
一个创业中的苦逼程序员
  • 回复
隐藏