python文件操作

打开文件

使用open()函数打开文件,并返回文件对象。并且其有3个参数。

open(name[, mode[, buffering]])

open的第1个参数:name

文件路径

open的第2个参数:mode

和其他语言的文件操作类似,文件有如下几种操作模式

'r'     read            读取,open默认参数即为读取
'w'     write           改写
'a'     append          追加
'b'     binary          二进制操作,可以添加到其他模式中
'+'     read + write    读写操作,可以添加到其他模式中

open的第3个参数:buffering

=0/False    不使用缓冲区
=1/True     使用缓冲区
>1          标明使用缓冲区大小(Bytes)
<0          使用默认缓冲区大小

文件的基本方法

三种标准流(类文件对象 class file object)

sys.stdin
sys.stdout
sys.stderr

read()和write()

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

# read()
f = open('somefile.txt', 'r')
print(f.read(4))
print(f.read())    # 读取剩下的字节
f.close()

管式输出 pipline output

管道符号 | 是将上一个命令的stdout和下一个命令的stdin连接在一起。
例如:

$ cat somefile.txt | python somescript.py | sort

上述命令将cat somefile.txt的输出结果输入到somescript.py中执行,并将结果出入到sort中去排序。

readline()和writeline()

f = open('somefile.txt', 'w')
f.writeline("this is 1st line")
f.writeline("this is 2nd line")
f.close()

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

close()

close会将留在内存中的缓存数据切实的写入磁盘中。并释放资源。

with语句

with是一个上下文管理器 context manager。
其支持 \__enter____exit__ 方法。

  • __enter__方法不带参数:进入with语句块时调用,返回值绑定到as之后的变量上。
  • __exit__方法带3个参数:异常类型,异常对象,异常回溯。

文件的 __enter__ 方法返回文件对象。__exit__ 方法关闭文件夹。

例如:

with open("somefile.txt", 'r') as f:
    pcross(f)

迭代文件内容

用while和for实现

with open("somefile.txt", 'r') as f:
    while True:
        # read(1)则变成按字节处理
        line = f.readline()
        if not line:
            break
        process(line)

with open("somefile.txt", 'r') as f:
    # 文件大时会占用大量内容,可用上述的while-readline代替
    for line in f.readlines():
    process(line)

用fileinput实现

fileinput已经包含open()功能。

import fileinput
# 只读取需要的部分
for line in fileinput.input("somefile.txt"):
    process(line)

文件迭代器

文件对象本身是可以迭代的。sys.stdin也可迭代。
所以,open()的返回对象可以不显示写出。

for line in open("somefile.txt"):
    process(line)

但最好还是显示的关闭文件。

f = open("somefile.txt"):
for line in f:
    process(line)
f.close()

list(open(file))等同于readlines

lines = list(open("somefile.txt"))
print(lines)

first, second, third = open("somefile.txt")
print("first:", first)
print("second:", second)
print("third:", third)

你可能感兴趣的:(python)