当前位置: 移动技术网 > IT编程>脚本编程>Python > Python创建文件和追加文件内容实例

Python创建文件和追加文件内容实例

2019年03月25日  | 移动技术网IT编程  | 我要评论

鸽子养殖大棚,一起又看流星雨全集优酷,喷潮争霸赛

一、用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")

例子:
查看22端口情况,并将结果写入a.txt
复制代码 代码如下:

 #!/usr/bin/python
#coding=utf-8
import os
import time
import sys
f=open('a.txt','a')
f.write(os.popen('netstat -nltp | grep 22').read())
f.close()

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网