咔叽游戏

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 520|回复: 0

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

[复制链接]
  • TA的每日心情
    无聊
    2019-4-21 13:02
  • 签到天数: 3 天

    [LV.2]圆转纯熟

    发表于 2020-5-1 12:14:22 | 显示全部楼层 |阅读模式
    一、用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()



    原文地址:https://www.jb51.net/article/56482.htm

    QQ|免责声明|小黑屋|手机版|Archiver|咔叽游戏

    GMT+8, 2024-3-29 06:50

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表