1

I have a python list similar to this:

my_list = ["hello", "bye", "good morning", "good evening", , "'yes", "''no'"]

Note that there may be some weird combination of quotation marks within a string.

I want to output it into a text file, however the quotation marks get lost in the process.

My code:

with open('/foo/bar.txt', 'w') as writefile:
     writefile.write('\n'.join(my_list))

My text file looks like this

hello
bye
good morning
...

I want it to look like this:

"hello"
"bye"
"good morning"
...
Exa
  • 466
  • 3
  • 16

3 Answers3

4

The quotation marks are only in the python syntax for marking a string. You can just write like this:

with open('/foo/bar.txt', 'w') as writefile: 
    writefile.write('"' + ('"\n"'.join(mylist)) + '"')

if this doesn't work, just use a for-loop to concatenate the strings with a f-string and voilá! :D

Fabian
  • 96
  • 5
4

Try this:

txt = ["hello", "bye", "good morning", "good evening", "yes", "no"]

with open("my_file.txt", "w") as f:
    f.writelines(f'"{w}"\n' for w in txt)

Output:

"hello"
"bye"
"good morning"
"good evening"
"yes"
"no"
baduker
  • 19,152
  • 9
  • 33
  • 56
1

one possible solution can be by using string literals. where ever you want such a character, just place a "\" sign before it, or to get a better understanding of it you can read about string literals here

my_list = ["\"hello\"", "bye", "good morning", "good evening", "'yes", "''no'"]

using this can also solve your problem

Pratik Agrawal
  • 405
  • 3
  • 17
  • Your method is the "hardcoded" one. The goal is to build code to be reused and this is not flexible in any way... Also, you would have to change your data and you usually do not want to do that – Fabian Jan 22 '21 at 12:04
  • I am not saying that you are wrong but one should also know about string literals and about data well we can use regex to fix that all in 2 go one for first quotation and other for the other one – Pratik Agrawal Jan 22 '21 at 12:14