如何在fi中处理这个整数数据

2024-06-02 05:03:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件A.txt作为:

000001 
0012
1122 
00192
..

文件大小约为25kb,每行都有一些随机数。你知道吗

我想用8位固定长度重新排列所有这些数字,如下输出:

00000001
00000012
00000112
00000192

我试过这个:

f = open('fileA.txt', 'r')
content = f.readlines()
nums = [ int(x.rstrip('\n')) for x in content]
print nums
f.close()

输出:

[1, 12, 1122, 192]

我想重新排列这些数字,甚至列表压缩挂起这里的原始文件。怎么做?你知道吗


Tags: 文件intxt列表forclose数字open
3条回答

使用str.format执行以下操作:

>>> with open('nums.txt') as f:
...     for line in f:
...         print('{:0>8}'.format(line.strip()))
... 
00000001
00000012
00001122
00000192

0是填充字符,>指定右对齐,8是填充字符串的宽度。你知道吗

您可以使用zfill方法,用“0”填充数字。你知道吗

nums = [ x.rstrip('\n').zfill(8) for x in content]
with open('test.txt') as f:
    for line in f:
        f_line = '{:08}'.format(int(line))
        print(f_line)

输出:

00000001
00000012
00001122
00000192

列表理解:

with open('test.txt') as f:
    lst = ['{:08}'.format(int(line)) for line in f]

输出:

['00000001', '00000012', '00001122', '00000192']

是的。你知道吗

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content. Preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '='.

format string syntax

相关问题 更多 >