Shivkumar kondi
Shivkumar kondi

Reputation: 6762

How to handle this integer data in file

I have a fileA.txt as :

000001 
0012
1122 
00192
..

The file is about 25kb with some random number on every line.

I want rearrange all these numbers with 8-digits fix length like the below output:

00000001
00000012
00000112
00000192

I tried this :

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

output:

[1, 12, 1122, 192]

I want to rearrange this numbers and even the list-compression gets hanged here for original file. How to do this?

Upvotes: 0

Views: 66

Answers (4)

宏杰李
宏杰李

Reputation: 12158

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

out:

00000001
00000012
00001122
00000192

List Comprehension:

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

out:

['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

Upvotes: 3

Roshan
Roshan

Reputation: 1459

if file is too large don't load all the data together and process it. Instead read line one by one and process each line one by one.

with open('fileA.txt', 'r') as f:
   with open('fileB.txt', 'w') as o: # newfile to fixed
       for line in f:
           val = line.strip('\n').zfill(8)
           print val
           o.write(val + '\n')

Upvotes: 2

snakecharmerb
snakecharmerb

Reputation: 55600

Use str.format to do this:

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

The 0 is the fill character, > specifies right-alignment and 8 is the width of the filled string.

Upvotes: 2

Maurice Meyer
Maurice Meyer

Reputation: 18106

You can use the zfill method, to fill your numbers with '0'.

nums = [ x.rstrip('\n').zfill(8) for x in content]

Upvotes: 2

Related Questions