Search code examples
pythonpython-3.xstringtext-filesread-write

Store a string as a single line in a text file


I have many big strings with many characters (about 1000-1500 characters) and I want to write the string to a text file using python. However, I need the strings to occupy only a single line in a text file.

For example, consider two strings:

string_1 = "Mary had a little lamb
which was as white
as snow"

string_2 = "Jack and jill
went up a hill 
to fetch a pail of
water"

When I write them to a text file, I want the strings to occupy only one line and not multiple lines.

text file eg:

Mary had a little lamb which was as white as snow
Jack and Jill went up a hill to fetch a pail of water

How can this be done?


Solution

  • If you want all the strings to be written out on one line in a file without a newline separator between them there are a number of ways as others here have shown.

    The interesting issue is how you get them back into a program again if that is needed, and getting them back into appropriate variables.

    I like to use json (docs here) for this kind of thing and you can get it to output all onto one line. This:

        import json
    
        string_1 = "Mary had a little lamb which was as white as snow"
    
        string_2 = "Jack and jill went up a hill to fetch a pail of water"
    
        strs_d = {"string_1": string_1, "string_2": string_2}
    
        with open("foo.txt","w") as fh:
            json.dump(strs_d, fh)
    

    would write out the following into a file:

    {"string_1": "Mary had a little lamb which was as white as snow", "string_2": "Jack and jill went up a hill to fetch a pail of water"}
    

    This can be easily reloaded back into a dictionary and the oroginal strings pulled back out.

    If you do not care about the names of the original string variable, then you can use a list like this:

        import json
    
        string_1 = "Mary had a little lamb which was as white as snow"
    
        string_2 = "Jack and jill went up a hill to fetch a pail of water"
    
        strs_l = [string_1, string_2]
    
        with open("foo.txt","w") as fh:
            json.dump(strs_l, fh)
    

    and it outputs this:

    ["Mary had a little lamb which was as white as snow", "Jack and jill went up a hill to fetch a pail of water"]
    

    which when reloaded from the file will get the strings all back into a list which can then be split into individual strings.

    This all assumes that you want to reload the strings (and so do not mind the extra json info in the output to allow for the reloading) as opposed to just wanting them output to a file for some other need and cannot have the extra json formatting in the output.

    Your example output does not have this, but your example output also is on more than one line and the question wanted it all on one line, so your needs are not entirely clear.