Home > front end >  Trouble with exporting a list to a txt file (formatting problem)
Trouble with exporting a list to a txt file (formatting problem)

Time:06-24

Python beginner here, having trouble with formatting when writing a list to a txt file. I want to export my list of books in a specific format, for comparison here is how my list currently looks when exported.

And here is how I want it to look. As you can see, we'll need some formatting.

The problem is, whenever I try to use the .replace function I get this error: https://i.imgur.com/0ZRW9uj.png

Here is the code in question. I've removed anything that causes errors.

def exportBooks():
    with open ('testbooks.txt', 'w') as f:
            f.write(str(books))
            print()
            print("Export complete.")
            print()
                    

I have to convert the list into a string or else the export won't work. Perhaps this same thing is linked to the error? What do you think we can do about this? I can post the rest of my code if requested in case you need more information, but does anyone have any ideas on the problem? How should it be coded here? Thank you very much.

CodePudding user response:

You are trying to write the python list structure as it is to the file where it includes all the extra characters (e.g. ",", "[", "]"). Instead you have to convert the list object in to a raw string format before writing. Try following.

def exportBooks():
    with open ('testbooks.txt', 'w') as f:
        f.write("\n".join(books))

CodePudding user response:

I think you must need to read the first file then write a text file? maybe this one can help you 
#first you need to read the file book right here
def exportBooks():
    with open('book.text') as books:
        return books.read().replace(',', ';')

#this will write the content of return value
    with open('write.text', 'w') as w:
        w.write(exportBooks())
  • Related