Chinaunix首页 | 论坛 | 博客
  • 博客访问: 392619
  • 博文数量: 77
  • 博客积分: 2031
  • 博客等级: 大尉
  • 技术积分: 855
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-15 19:54
文章分类

全部博文(77)

文章存档

2011年(1)

2009年(52)

2008年(24)

我的朋友

分类: LINUX

2009-03-03 20:48:50

#!/usr/bin/python
# Filename: readfile.py

header = '''\
abc
def
ghi
jkl
mno
'''

f = file('header.txt', 'w') # open for 'w'riting
f.write(header) # write text to file
f.close() # close the file

f = file('header.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()
    if len(line) == 0: # Zero length indicates EOF
        break
    print line,
    # Notice comma to avoid automatic newline added by Python
f.close() # close the file


一、用Python创建一个新文件,内容是从0到9的整数, 每个数字占一行:
>>>f=open('f.txt','w')    # r只读,w可写,a追加
>>>for i in range(0,10):f.write(str(i)+'\n')
.  .  .
>>> f.close()

二、文件内容追加,从0到9的10个随机整数:
>>>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行:
>>> 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()

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

>>>  . . .


阅读(1785) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~