1

I am trying to write the contents of 2d list in a specific pattern that needs to be read by another file too. After writing the code, The text file mess up. Help me out from this issue.Thanks

I have tried using a loop to write the contents to text file but I failed.

list_final=[['Harry Potter', 'JK Rowling', '55', '2'], ['Start With Why', 'Simon Sinek', '42', '1.5'], ['P With Python', 'John Smith', '40', '1.5']]

file_contain_db_write = open("books.txt", "w")
for each in list_final:
    file_contain_db_write.write(str(", ".join(str(each))))
    file_contain_db_write.write("\n")
file_contain_db_write.close()

My expected result:

My code output:

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ankit Shah
  • 1,087
  • 2
  • 15
  • 30
  • 3
    Hello, please post results as text. – iGian Jan 05 '19 at 06:47
  • You could use JSON as a common data format. See [this](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file). – FThompson Jan 05 '19 at 06:48
  • [, ', H, a, r, r, y, , P, o, t, t, e, r, ', ,, , ', J, K, , R, o, w, l, i, n, g, ', ,, , ', 5, 5, ', ,, , ', 2, ', ] [, ', S, t, a, r, t, , W, i, t, h, , W, h, y, ', ,, , ', S, i, m, o, n, , S, i, n, e, k, ', ,, , ', 4, 2, ', ,, , ', 1, ., 5, ', ] [, ', P, , W, i, t, h, , P, y, t, h, o, n, ', ,, , ', J, o, h, n, , S, m, i, t, h, ', ,, , ', 4, 0, ', ,, , ', 1, ., 5, ', ] – Ankit Shah Jan 05 '19 at 06:48
  • actually, it's a college project. The guideline says us to write in a text file. So, I can't use JSON in this case. – Ankit Shah Jan 05 '19 at 06:51

1 Answers1

2

Get rid of both str calls. The inner one produces Python’s representation of a list rather than using its contents, and the outer one is being applied to something that is already a string. (Try testing small pieces of your code in the REPL to avoid these issues.)

Davis Herring
  • 36,443
  • 4
  • 48
  • 76