Home > Software engineering >  How to print horizontally when writing into a text file?
How to print horizontally when writing into a text file?

Time:06-13

I'm trying to print the output like this in a text file:

Bruce Wayne
5 5 0 0 100 15
Jessica Jones
12 0 6 6 10 6
Johnny Rose
6 2 0 4 20 10
Gina Linetti
7 4 0 3 300 15
Buster Bluth
3 0 2 1 50 1

But with my code here:

def write_to_file(filename, player_list):
    outfile = open(filename, "w")

    for i in range(len(player_list)):
        for j in player_list[i]:
           outfile.write(str(j)   '\n')

    outfile.close()

It prints out like this:

Bruce Wayne
5
5
0
0
100
15
Jessica Jones
12
0
6
6
10
6
Johnny Rose
6
2
0
4
20
10
Gina Linetti
7
4
0
3
300
15
Buster Bluth
3
0
2
1
50
1

player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15], ['Jessica Jones', 12, 0, 6, 6, 10, 6], ['Johnny Rose', 6, 2, 0, 4, 20, 10], ['Gina Linetti', 7, 4, 0, 3, 300, 15], ['Buster Bluth', 3, 0, 2, 1, 50, 1]]

and I'm not sure how to get the bottom row to print horizontally like the output I have above. I'm not allowed to use any list functions and I have to use a loop, as seen with my code. Thank you!

CodePudding user response:

You can't treat all the contents of your player_list the same, because the values mean different things. The first value is the player name, the rest are scores or something. So your code needs to put a newline after the first value, but only spaces between the rest (with a newline at the end of the second line).

Try something like this:

def write_to_file(filename, player_list):
    outfile = open(filename, "w")

    for player_name, *scores in player_list:   # unpack first value separately
        outfile.write(player_name   "\n")
        outfile.write(" ".join(str(score) for score in scores)   "\n")
        
    outfile.close()

Unrelatedly, you might want to use with to handle your file object. It will close the file automatically for you, even if there's an exception:

with open(filename, "w") as outfile:
    for blah in ...:
        ...
# no need to manually call close(), it will happen automatically here

CodePudding user response:

do like so

def write_to_file(filename, player_list):
    outfile = open(filename, "w")

    for i in range(len(player_list)):
        for j in player_list[i]:
           outfile.write(str(j))
        outfile.write('\n')

    outfile.close()

CodePudding user response:

You need to separate the player name from the values.

def write_to_file(filename, player_list):
    outfile = open(filename, "w")

    for lst in player_list:
        player = lst[0]
        values = lst[1:]

        outfile.write(player   '\n'   " ".join([str(num) for num in values])   '\n')


    outfile.close()
  • Related