python碎片整理

1、获取文件长度,有两种方法。

a、打开文件,seek到文件末尾,通过tell方法返回当前位置即文件长度.

binFile = open('test', 'rb')
binFile.seek(0,os.SEEK_END)
size = binFile.tell()
binFile.seek(0,os.SEEK_SET)

b、通过os.path.getsize获取

size2 = os.path.getsize('test')
print size, size2



2、文件与数组互相操作

a、从文件导入数据到数组

ds = array.array('B')
ds.fromfile(binFile, 400)
print ds


b、把数组数据保存成文件

fout = open('save', 'wb')
ds.tofile(fout)


3、字符串调整长度

strtest = '123'.ljust(8, b'\x00')
print strtest

string.ljust(s,width[, fillchar]) string.rjust(s,width[, fillchar]) string.center(s,width[, fillchar])

These functions respectively left-justify, right-justify and center a string in a field of given width. They return a string that is at leastwidth characters wide, created by padding the string s with the characterfillchar (default is a space) until the given width on the right, left or both sides. The string is never truncated.

string.zfill(s,width)

Pad a numeric string s on the left with zero digits until the given width is reached. Strings starting with a sign are handled correctly.


4、把数据转为结构

strtest = '123'.ljust(8, b'\x00')
print strtest

print b''.join(struct.pack('I', 10))

struct. pack ( fmt , v1 , v2 , ... )

Return a string containing the values v1, v2, ... packed according to the given format. The arguments must match the values required by the format exactly.

struct. pack_into ( fmt, buffer, offset, v1, v2, ... )

Pack the values v1, v2, ... according to the given format, write the packed bytes into the writable buffer starting at offset. Note that the offset is a required argument.


5、INI配置文件操作

pip安装configparser这个库

config = configparser.ConfigParser()
config.read('test.ini')
for section in config.sections():
    print section



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值