zoukankan      html  css  js  c++  java
  • 零基础学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-目录

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

  • 相关阅读:
    SQL-修改表名,列名
    MySQL必知必会-7、数据过滤
    排序
    Leetcode题解-双指针
    MySQL必知必会-6、过滤数据
    MySQL必知必会-5、排序检索数据
    MySQL必知必会-4、检索数据
    Java容器源码分析-LinkedList
    Java容器源码分析-CopyOnWriteArrayList
    Java容器源码分析-Vector
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4774468.html
Copyright © 2011-2022 走看看