Home > Enterprise >  python write(string) saves normally but sometimes it saves as a list of characters
python write(string) saves normally but sometimes it saves as a list of characters

Time:01-24

I've the following simple function which saves a string to a file:

def writeFile(path, data):
    with open(path, mode = 'wt', encoding="utf-8") as file:
        file.write("".join(data))
        file.close()

I tried to use file.write(data) and then I replaced data with "".join(data) but it doesn't change anything. Most of the time, the string is saved normally but sometimes, it is saved as a list of characters, meaning that each character of the string is separated by \n and I don't understand why.

CodePudding user response:

There are several things going on here:

First of all, "".join(data) doesn't change the string - it breaks up data into characters, and then just join it back together to the original string. Therefore the newlines that are causing your issue - are in the original string.

Secondly, as you are using the context manager, there is no need to use file.close - the context manager automatically closes the file.

CodePudding user response:

thx for your support, I made a new function converting my list into a string

def listToString(aList):
    retStr = lf = ""
    for element in aList:
        retStr = f"{retStr}{lf}{element}"
        lf = "\n"
    return retStr

def writeFile(path, data):
    with open(path, mode = 'wt', encoding="utf-8") as file:
        file.write(data)

data = ["12","34","45","..."]
writeFile("data.txt", listToString(data))
  •  Tags:  
  • Related