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.


1           Dave
           234           Einstein 
        100000           Bob
for i in range(len(arr)):


Recommended Answers

All 2 Replies

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)


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

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]))
Printing out to file 'test123.txt' ...
         1                           Dave 
       234                       Einstein 
    100000                            Bob
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.