在python下file类型、open方法

来源:互联网 发布:如何下载英语翻译软件 编辑:程序博客网 时间:2024/05/17 02:45

python中file和open有什么区别?

file 估计是一种类型, 代表一个文件, 而open 是一个方法,代表一个动作。打开文件的动作,相应的应该还有close, 关闭文件。



一、用Python创建一个新文件,内容是从0到9的整数, 每个数字占一行:

#python
>>>f=open('f.txt','w')    # r只读,w可写,a追加
>>>for i in range(0,10):f.write(str(i)+'\n')
.  .  .
>>> f.close()

二、文件内容追加,从0到9的10个随机整数:
#python
>>>import random
>>>f=open('f.txt','a')
>>>for i in range(0,10):f.write(str(random.randint(0,9)))
.  .  .
>>>f.write('\n')
>>>f.close()

三、文件内容追加,从0到9的随机整数, 10个数字一行,共10行:
#python
>>> import random
>>> f=open('f.txt','a')
>>> for i in range(0,10):
.  .  .     for i in range(0,10):f.write(str(random.randint(0,9))) 
.  .  .     f.write('\n')    
.  .  .
>>> f.close()

四、
把标准输出定向到文件:
#python
>>> import sys
>>> sys.stdout = open("stdout.txt", "w")

>>>  . . .
原创粉丝点击