zoukankan      html  css  js  c++  java
  • python 文件处理 -- 02 文件属性&标准输入输出&命令行参数&文件编码

    1文件属性

    file.fileno()--文件描述符

    file.mode--文件当前打开的权限

    file.encoding--文件编码格式(无输出表明为ASCII码)

    file.closed--文件是否被关闭

    >>> f.fileno()

    3

    >>> f.mode

    'r+'

    >>> f.encoding

    >>> f.closed

    False

    >>> filter(lambda s:s[:2]!='__',dir(f))

    ['close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

    2标准文件

    标准输入文件--sys.stdin

    标准输出文件--sys.stdout

    标准错误文件--sys.stderr

    可以使用这三者来实现将python程序运行的stdout和stderr重定向到文件

    例--重定向stdout

    #stdout.py

    import sys

     

    print 'Dive in'

    saveout = sys.stdout

    fsock = open('out.log', 'w')

    sys.stdout = fsock # 此处之后的print就会被打印到out.log中

    print 'This message will be logged instead of displayed'

    sys.stdout = saveout

    fsock.close()   #还原stdout

    参考:http://blog.csdn.net/lanbing510/article/details/8487997

    3文件命令行参数

    通过sys模块的argv属性来接收命令行参数。返回一个list,list[0]为脚本名,list[1:]均为参数。

    ***argv.py文件内容

    # argv.py

    import sys

    print 'test----'

    argv_list = sys.argv

    print argv_list

    ***命令行调用

    E:yc_studypython系统学习--慕课网文件处理>python argv.py 1 2 3

    test----

    ['argv.py', '1', '2', '3']

     

    E:yc_studypython系统学习--慕课网文件处理>python argv.py 1 2 age=18

    test----

    ['argv.py', '1', '2', 'age=18']

     

    4文件编码格式

    4.1Python字符编码详解

             http://www.cnblogs.com/timdes1/p/7747589.html

    4.2写入utf-8格式的字符串

    >>> f=open('unicode_test.txt','w+')

    >>> f.read()

    ''

    >>> f.write(u'哈哈哈')

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

    >>> des_str=unicode.encode(u'哈哈哈','utf-8')

    >>> f.write(des_str)

    >>> f.seek(0,os.SEEK_SET)

    >>> f.read()

    'xe5x93x88xe5x93x88xe5x93x88'

    4.3创建utf-8格式的文档

    使用codecs模块

    >>> f=codecs.open('create_utf_8.txt','w','utf-8')

    >>> f.encoding

    'utf-8'

    >>> f.close()

  • 相关阅读:
    Spring4 MVC json问题(406 Not Acceptable)
    java 从网络Url中下载文件
    Java基础知识(一) 自增、自减运算符
    java文件读写操作
    java集合运算:求交集,并集,集合差
    httpclient+jsoup实现网页信息抓取
    java web使用gradle配置详情
    关于mysql登录异常处理方法
    windows server 2012 r2 远程桌面连接指南
    Java生成带小图标的二维码-google zxing 工具类
  • 原文地址:https://www.cnblogs.com/yc913344706/p/7764332.html
Copyright © 2011-2022 走看看