cls_404
cls_404

Reputation: 56

Removing line break and writing lists without square brackets and comas to a text file in python

I'm facing a few issues with regard to writing some arguments to a text file. Below are the outputs I need to see in my text file.

  1. I want to write an output like this to the text file.
    Input:
Hello
World

Output: HelloWorld

2. I want to write an output like this into a text file.
Input:

[1, 2, 3, 4, 5]

Output: 1,2,3,4,5

I tried several ways to do this but couldn't find a proper way.
Hope to seek some help.

The Code:

progressList = [120, 0, 0] #A variable which wont change. (ie this variable only has this value))
resultList = ['Progress', 'Trailer'] #Each '' represents one user input

#loop for progress
with open("data.txt", "a") as f: # Used append as per my requirement
    i = 0 #iterator

    while i < len(resultList):
        # f.write(resultList)

        if resultList[i] == "Progress":
            j = 0
            f.write("Progress - ")
       
            for j in range(3):

                while j < 2:
                    f.write(', ', join(progressList[j]))
                    break

                if j == 2:
                    f.write(progressList[j], end='')
                    break

Output (textfile):
Progress - 120, 0, 0

Thanks.

Upvotes: -1

Views: 78

Answers (1)

Oleh Kostiv
Oleh Kostiv

Reputation: 11

1st case would be something like this

>>> s = '''hello
... world'''
>>> ''.join(s.split())
'helloworld'
>>>

2nd one is funny

>>> s = "[1, 2, 3, 4, 5]"
>>> exec ('a = ' + s)
>>> ','.join([str(i) for i in a])
'1,2,3,4,5'

hope it helps

Upvotes: 0

Related Questions