Python内置函数_IO操作类

来源:互联网 发布:优酷不允许移动数据下 编辑:程序博客网 时间:2024/05/08 13:38

file

file(filename [, mode [, bufsize]])file类型的构造函数,作用为打开一个文件,如果文件不存在且mode为写或追加时,文件将被创建。添加„b‟到mode参数中,将对文件以二进制形式操作。添加„+‟到mode参数中,将允许对文件同时进行读 写操作  1、参数filename:文件名称。 2、参数mode:'r'(读)、'w'(写)、'a'(追加)。  3、参数bufsize:        如果为0表示不进行缓冲,        如果为1表示进行行缓冲,        如果是一个大于1的数表示缓冲区的大小 。  
In [1]: f1 = file('test1.txt','w+')In [2]: s = '1 GOOGLE Inc\n2 Microsoft Corporation\n3 Apple Inc\n4 Facebook Inc'In [3]: f1.writelines(s)In [4]: f1.flush()In [5]: f1.close()In [6]: f2 = file('test1.txt','r+')In [7]: names = f2.readlines()In [8]: for i in names:   ...:     print i   ...:1 GOOGLE Inc2 Microsoft Corporation3 Apple Inc4 Facebook Inc

input & raw_input

input([prompt])  & raw_input([prompt])
input 与 repr相似的是两者都要精确,raw_input与str相似的是两者都要可读
>>> var = input('please input')please input3>>> type(var)<type 'int'>>>> var = input('please input')please input'hello'>>> type(var)<type 'str'>>>> var = input('please input')please inputrange(10)>>> type(var)<type 'list'>>>> var = input('please input')please input helloTraceback (most recent call last):  File "<pyshell#9>", line 1, in <module>    var = input('please input')  File "<string>", line 1, in <module>NameError: name 'hello' is not defined>>> var = raw_input('please input')please input3>>> type(var)<type 'str'>>>> var = raw_input('please input')please input range(10)>>> type(var)<type 'str'>>>> var = raw_input('please input')please input hello

open

open(filename [, mode [, bufsize]])open类型的构造函数,作用为打开一个文件,如果文件不存在且mode为写或追加时,文件将被创建。添加„b‟到mode参数中,将对文件以二进制形式操作。添加„+‟到mode参数中,将允许对文件同时进行读 写操作  1、参数filename:文件名称。 2、参数mode:'r'(读)、'w'(写)、'a'(追加)。  3、参数buffering:        如果为0表示不进行缓冲,        如果为1表示进行行缓冲,        如果是一个大于1的数表示缓冲区的大小 。  
In [1]: f1 = open('test1.txt','w+')In [2]: s = '1 GOOGLE Inc\n2 Microsoft Corporation\n3 Apple Inc\n4 Facebook Inc'In [3]: f1.writelines(s)In [4]: f1.flush()In [5]: f1.close()In [6]: f2 = open('test1.txt','r+')In [7]: names = f2.readlines()In [8]: for i in names:   ...:     print i   ...:1 GOOGLE Inc2 Microsoft Corporation3 Apple Inc4 Facebook Inc
0 0
原创粉丝点击