1

Is there any way to add new records in the file with each field occupying specific size using python? As shown in below picture, there are together 8 columns [column number:column bytes] ->[1:20,2:10,3:10,4:39, 6:2, 7:7,8:7] each of different size. For example if first column value is of 20 bytes "ABBSBABBSBT ", this can contain either 10,5 or can occupy entire 20 bytes depending upon user input. In C language, we can specify the byte size during the variable initialization. How one can add new record with proper fixed spacing for each column?

enter image description here

Thank you in advance!

J...S
  • 5,079
  • 1
  • 20
  • 35
Christie
  • 19
  • 8
  • 2
    Use code blocks to help others interpret your code and question better. https://stackoverflow.com/editing-help – Ari Mar 12 '19 at 11:12

2 Answers2

0

You can use Python's formatting syntax to format the string before appending to the file. Something like:

line_format = '{:20}{:10}{:10}{:39}{:2}{:7}{:7}\n'

with open('existing_file', 'a') as f:
    f.write(line_format.format('ABBSBABBSBT', 'JP000', 'XYZABC', 'JPJPYJAP', 0, 'YYSGB', '00NABCD'))

You can use said syntax above to specify the maximum width and the justification too, among many other useful options.

Nobilis
  • 7,310
  • 1
  • 33
  • 67
0

You can also use f-string literals, which are available since Python3.6, for this.

You cold write an f-string like

out_str = f"{col1:20}{col2:10}{col3:39}{col4:2}{col5:1}{col6:2}{col7:7}{col8:7}")

to the file.

col1, col1, col1, etc are variables having the value of the columns. Substitute your variable names.

The number after the : is the width over which the value should be printed over. By default it is left-aligned.

For example:

col1="MEGAXXXX"
col2="CO415"
col3="WWE42AWE42AWE42AWE42AE42A"
col4="Z"
col5="1"
col6="M"
col7="4j4241"
col8="234"

print(f"{col1:20}{col2:10}{col3:39}{col4:2}{col5:1}{col6:2}{col7:7}{col8:7}")

would give

MEGAXXXX            CO415     WWE42AWE42AWE42AWE42AE42A              Z 1M 4j4241 234   

This might also help.

J...S
  • 5,079
  • 1
  • 20
  • 35
  • Thank you J...S, your solution is working as well. Unfortunately I can mark only one as a answer here :) – Christie Mar 13 '19 at 05:19