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_study\python\系统学习--慕课网\文件处理>python argv.py 1 2 3

test----

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

 

E:\yc_study\python\系统学习--慕课网\文件处理>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()

'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'

4.3创建utf-8格式的文档

使用codecs模块

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

>>> f.encoding

'utf-8'

>>> f.close()

posted @ 2017-10-31 23:00  yc紫日  阅读(335)  评论(0编辑  收藏  举报