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
fout = open('save', 'wb')
ds.tofile(fout)
strtest = '123'.ljust(8, b'\x00')
print strtest
-
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.
ljust
(s,width[, fillchar])
string.
rjust
(s,width[, fillchar])
string.
center
(s,width[, fillchar])
-
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.
-
string.
zfill
(s,width)
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.
-
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.
struct.
pack_into
(
fmt,
buffer,
offset,
v1,
v2,
...
)
5、INI配置文件操作
pip安装configparser这个库
config = configparser.ConfigParser()
config.read('test.ini')
for section in config.sections():
print section