1

My code in python is

file.write("Name\t Age\t M/F\t")
file.write("Mo\t 15\t M\t")

yet it comes out

Name   Age  M/F
Mo 15 M

The columns are not in line as in they are all not in the same column. Is there a command to sort it out so it saves and prints in one column and line?

1
  • What is the expected output and what is the error? I don't fully get what "not in line" means. Also, please use the code formatting tools provided by SO; I took care of it this time. Commented Mar 12, 2016 at 19:26

4 Answers 4

3

It's all about string formatting (check the string format documentation). You can do the following:

fmt = '{0:10s}{1:10s}{2:10s}'
file.write(fmt.format('Name', 'Age', 'M/F'))
file.write(fmt.format('Mo', '15', 'M'))
# Name      Age       M/F       
# Mo        15        M  

In the format {0:10s}, the s means that the variable you want to write is a string and the 10 means that you want the output to be 10 characters long.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use .format() with a specification of how many chars the entry should have: {:10s} for 10 chars.

Here is an example:

with open('name.txt', 'w') as file:
    file.write('{:10s}{:10s}{:10s}\n'.format('Name', 'Age', 'M/F'))
    file.write('{:10s}{:10s}{:10s}\n'.format('Mo', '15', 'M'))

leading to

Name      Age       M/F       
Mo        15        M         

Comments

1

I tried

file=open("test.txt","wb")
file.write("Name\t Age\t M/F\t")
file.write("Mo\t 15\t M\t")
file.close()

and Got

Name     Age     M/F    Mo   15  M  

because as for windows you need \r\n for new line but that was the only problem.

with

file=open("test.txt","w")
file.write("Name\t Age\t M/F\n")
file.write("Mo\t 15\t M")
file.close()

output in file was was

Name     Age     M/F
Mo       15      M

So the code is working on Linux and windows dude.

What are you running it on anyway?

1 Comment

Different tab stop size maybe?
0

You can do it with python string formating.

fmt = '{0:<30} {1:<10} {2:<10}'

file.write(fmt.format("Name","Age","M/F"))
file.write(fmt.format("Mo","15","M"))

Output:

Name                           Age        M/F       
Mo                             15         M       

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.