Python创建文件和追加文件内容实例
一、用Python创建一个新文件,内容是从0到9的整数,每个数字占一行:
#python
>>>f=open('f.txt','w') #r只读,w可写,a追加
>>>foriinrange(0,10):f.write(str(i)+'\n')
. . .
>>>f.close()
二、文件内容追加,从0到9的10个随机整数:
#python
>>>importrandom
>>>f=open('f.txt','a')
>>>foriinrange(0,10):f.write(str(random.randint(0,9)))
. . .
>>>f.write('\n')
>>>f.close()
三、文件内容追加,从0到9的随机整数,10个数字一行,共10行:
#python
>>>importrandom
>>>f=open('f.txt','a')
>>>foriinrange(0,10):
. . . foriinrange(0,10):f.write(str(random.randint(0,9)))
. . . f.write('\n')
. . .
>>>f.close()
四、把标准输出定向到文件:
#python
>>>importsys
>>>sys.stdout=open("stdout.txt","w")
例子:
查看22端口情况,并将结果写入a.txt
#!/usr/bin/python
#coding=utf-8
importos
importtime
importsys
f=open('a.txt','a')
f.write(os.popen('netstat-nltp|grep22').read())
f.close()
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短