Reputation: 19
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?
Upvotes: 1
Views: 186
Reputation: 1306
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?
Upvotes: 1
Reputation: 9018
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
Upvotes: 0
Reputation: 336
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
Upvotes: 2
Reputation: 15443
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.
Upvotes: 3