Search code examples
pythonserializationreplacefindpyscripter

how do i find and replace items in a text file in pyscripter?


how do i find and replace items in a text file in pyscripter?

In a script, I have put a list into a text file by converting it to a string. now it has square brackets in. I need to remove these so I can take out individual words and numbers. I need a script that will allow me to find and replace these brackets with "nothing".

please help!

this is what my text file currently looks like. 1


Solution

  • First of all, when you need to store a list in a file, use JSON, pickle or equivalent. JSON is preferred for long-term storage as well as for storage meant to be read by other programs, or sent over the wire:

    import json
    
    my_list = ["hello", "world"]
    
    with open('file.txt', 'w') as f:
        json.dump(my_list, f)
    

    Or, if all you want to do is store one word/sentence/phrase per line in plain text format:

    my_list = ["hello", "world"]
    with open('file.txt', 'w') as f:
        f.write('\n'.join(my_list))  # assuming your list isn't large
        f.write('\n')
    

    (pickling, on the other hand, is good for temporary/internal storage, as well as storage of stuff you cannot convert into a form that JSON can handle; for more information, just find the documentation of the pickle module.)

    Now, if you've screwed up and just put the string representation of a list into the file, you either clean it up manually, or you use the following helper:

    import ast
    import json
    
    with open('file.txt') as f:
        contents = f.read()
    contents = ast.literal_eval(contents)  # parses the string as if it were a Pytnon literal (which it is)
    
    with open('file.txt', 'w') as f:
        json.dump(contents, f)  # write back as JSON this time
    

    If your file contains multiple lists, each on a separate line, you can use this:

    import ast
    import json
    
    with open('file.txt') as f:
        lines = f.read().split('\n')
    contents = [ast.literal_eval(line) for line in lines]
    
    # ...and now choose from above how you'd like to write it back to the file
    

    NOTE: oh and... this really seems to have nothing to do with pyscripter, unless I've missed something.