python之文件操作

python文件操作

举例:将一个文本文件转成十六进制形式后,保存到另一个文件中。

f = open('mycert.cr', 'r')

str = f.read()

list = []

for ch in str:

    list.append(hex(ord(ch)))

file_object = open('mycert.txt', 'w')

print >> file_object, list

file_object.close()

说明:

1、python的open函数,获得一个文件句柄;

f = open('test.cer', 'r')

2、python的read函数,获得一个字符串;

str = f.read()

3、一个个获取字符串中的字符;

for ch in str:

4、将字符ch转成十进制整数;

ord(ch) 例如: ord('a') returns the integer 97

5、将十进制整数转成十六进制整数;

hex(x) 例如:97(十进制) -> 61(十六进制)

6、创建一个序列;

list = []

7、将字符添加到list中;

list.append(hex(ord(ch)))

8、将list中的内容写到file_object文件中;

print >> file_object, list

 

posted on 2016-09-30 15:15  小生有悔  阅读(192)  评论(0编辑  收藏  举报

导航