• 零基础学python-9.2 文件


    1.文件的操作:

    操作

    解释

    output=open(r'c:123.txt','w')

    创建输出文件,w写入

    input=open('data','r')

    创建输出文件,r读取

    input=open('data')

    创建输出文件,r默认

    s=input.read()

    整个文件读取单一字符串

    s=input.read(N)

    读取之后的n个字节到字符串

    s=input.readline()

    读取下一行到一个字符串

    alist=input.readlines()

    读取整个文件到字符串列表

    output.write(s)

    写入字节字符串到文件

    output.writelines(list)

    把列表内所有字符串写入文件

    output.close()

    手动关闭

    output.flust()

    清空缓存

    anyFile.seek(N)

    查询

    for line in open('data'):use line

    逐行读取

    open('f.txt',encodeing='latin-1')

    设置unicode

    open('f.bin','rb')

    2.基本操作实例

    >>> myfile=open('123.txt','w')
    >>> myfile.write
    <built-in method write of _io.TextIOWrapper object at 0x012D8D30>
    >>> myfile.write('hello world 
    ')
    13
    >>> myfile.write('hello world 2 
    ')
    15
    >>> myfile.close ()
    >>> myfile=open('123.txt')
    >>> myfile.readline
    <built-in method readline of _io.TextIOWrapper object at 0x0170B5B0>
    >>> myfile.readline ()
    'hello world 
    '
    >>> myfile.readline ()
    'hello world 2 
    '
    >>> myfile.readline ()
    ''
    >>> 


    上面是读取、写入文件

    3.只有字符串才能够写入文件

    >>> myfile=open('123.txt','w')
    >>> l=(1,2,3)
    >>> myfile.write(l)
    Traceback (most recent call last):
      File "<pyshell#30>", line 1, in <module>
        myfile.write(l)
    TypeError: must be str, not tuple
    >>> 
    >>> t=[1,2,3]
    >>> myfile.write(t)
    Traceback (most recent call last):
      File "<pyshell#35>", line 1, in <module>
        myfile.write(t)
    TypeError: must be str, not list
    >>> 



     

    就说到这里,谢谢大家

    ------------------------------------------------------------------

    点击跳转零基础学python-目录

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    kafka集群partition分布原理分析
    Kafka的通讯协议
    RabbitMQ和Kafka
    深入理解kafka设计原理
    Kafka的Log存储解析
    Netty 超时机制及心跳程序实现
    Netty 实现 WebSocket 聊天功能
    Netty 实现聊天功能
    RabbitMQ在分布式系统中的应用
    Kafka文件存储机制那些事
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4774468.html
Copyright © 2020-2023  润新知