0

I have a text file in which i wrote a list. Now i want to join all the list items in that text file. Here is the screenshot of the contents of text file The content of my text file

I tried doing this:

    file = open("Result.txt","r+",encoding="utf8")
    text = file.read()
    text.join(' ')

but it prints ' '

Tab Key
  • 171
  • 2
  • 15

2 Answers2

2

You should parse the file content with ast.literal_eval to turn it into an actual list first, and then use the str.join method to join the list items into one string:

from ast import literal_eval

with open("Result.txt","r+",encoding="utf8") as file, open('output.txt', 'w') as output:
    output.write(' '.join(literal_eval(file.read())))
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • but it doesn't change the contents of the file.. how to update the file or write it to a new text file? @blhsing – Tab Key Oct 17 '18 at 10:27
  • I've updated my answer with how you can write the output to a new text file `output.txt`. – blhsing Oct 17 '18 at 10:34
0

You are given a string.

trim the brackets with

text = text[1:-1]

Then remove the "'" and ","

text.replace("'", "").replace(",","")

You can also remove the '\\n' the same way.

THEOS
  • 59
  • 5
  • i was using join because i want to join the words in a sentence but separate the sentences from each other from making the use of \n – Tab Key Oct 17 '18 at 10:19