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

作者:junjie 时间:2021-03-15 04:38:09 

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

标签:Python,创建文件,追加文件内容
0
投稿

猜你喜欢

  • 源码解析python的内存回收机制

    2023-05-19 18:12:16
  • Python使用psutil获取进程信息的例子

    2021-11-03 07:29:47
  • Python 实现「食行生鲜」签到领积分功能

    2023-02-25 16:26:00
  • JavaScript中window.showModalDialog()用法详解

    2024-04-18 09:48:04
  • Python 机器学习工具包SKlearn的安装与使用

    2023-11-10 13:13:05
  • 在CentOS上MySQL数据库服务器配置方法

    2024-01-19 07:01:21
  • mysql连接查询详解

    2024-01-15 16:42:11
  • 六个Python编程最受用的内置函数使用详解

    2022-06-12 22:26:01
  • JS获取url参数,JS发送json格式的POST请求方法

    2024-04-30 10:10:27
  • python使用super()出现错误解决办法

    2021-05-01 02:48:48
  • python中正则的使用指南

    2023-09-10 18:24:51
  • Python3利用Dlib19.7实现摄像头人脸识别的方法

    2022-08-08 06:41:22
  • 设置python3为默认python的方法

    2023-07-11 19:24:49
  • 一文弄懂Pytorch的DataLoader, DataSet, Sampler之间的关系

    2022-06-27 14:21:53
  • JS常见错误(Error)及处理方案详解

    2024-04-22 22:24:34
  • Python中的pprint模块

    2022-02-07 17:02:42
  • Python实现arctan换算角度的示例

    2023-07-16 20:31:28
  • php动态函数调用方法

    2023-11-15 00:18:30
  • Go container包的介绍

    2024-04-28 10:49:08
  • 深入理解TCP协议与UDP协议的原理及区别

    2022-11-06 21:30:31
  • asp之家 网络编程 m.aspxhome.com