0

Hello,

I want to write to a file in a particular format. There should be 2 columns, the first column should allocate 5 spaces to store digits and the next column should allocate 30 spaces to store characters.

Ex:-

1           Dave
           234           Einstein 
        100000           Bob
              .
              .
              .
for i in range(len(arr)):
		temp=arr[i]
		add=i,temp
		wordlist.write(str(add))
		wordlist.write('\n')
	wordlist.close()

Thanks.

Edited by vegaseat: n/a

3
Contributors
2
Replies
5
Views
6 Years
Discussion Span
Last Post by richieking
0

If you use Python3, you can apply formatting this way ...

# needs Python3

data_list = [
(1, 'Dave'),
(234, 'Einstein'), 
(100000, 'Bob')
]

print("Printing out to file 'test123.txt' ...")
fout = open("test123.txt", "w")
for item in data_list:
    sf = "{0:>10d}          {1:30}"
    # show on the screen as a test
    print(sf.format(item[0], item[1]))
    # redirect print() to a file
    print(sf.format(item[0], item[1]), file=fout)

fout.close()

With older versions of Python you can use the % formatting directive, similar to the one used in the C language.

Edited by vegaseat: w

0

Try this c style

data_list = [
(1, 'Dave'),
(234, 'Einstein'), 
(100000, 'Bob')
]
print("Printing out to file 'test123.txt' ...")
with open("test123.txt", "w")as fout:
  fout.write("".join(["%10d %30s \n"%(x[0],x[1]) for x in data_list]))
  print("".join(["%10d %30s \n"%(x[0],x[1]) for x in data_list]))
###output
Printing out to file 'test123.txt' ...
         1                           Dave 
       234                       Einstein 
    100000                            Bob

Edited by richieking: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.