简体   繁体   中英

Make a file more readable

Say we have a file with the following inside:

{{{banana},{kinky},{bronze-spaghetti,
definitly-not},{legitimate-style, witness,
drunk}}}

I wanted to rearrange this file so that it look like this:

{{{banana},
{kinky},
{bronze-spaghetti,definitly-not},
{legitimate-style, witness, drunk}}}

Notice that each line ends with }, except for the last one. Now my question is how would I do this?

you can find the regex "}," and insert after it a new line

edit: as jDo suggested, you can do something like that:

with open('in.txt', 'r') as infile:
    data=infile.read()
with open('out.txt', 'w') as outfile:
    outfile.write(data.replace("\n", "").replace("},", "},\n"))

I think you could simply use replace (triple quotes for multi-line strings):

original_text = """{{{banana},{kinky},{bronze-spaghetti, definitly-not},{legitimate-style, witness, drunk}}}"""
reformatted = original_text.replace("\n", "").replace("},", "},\n")
print(reformatted)

This can easily be done in the shell:

>>> my_str = """{{{banana},{kinky},{bronze-spaghetti,
... definitly-not},{legitimate-style, witness,
... drunk}}}"""
>>> 
>>> my_str = my_str.replace("\n", "").replace("},", "},\n")
>>> 
>>> print(my_str)
{{{banana},
{kinky},
{bronze-spaghetti,definitly-not},
{legitimate-style, witness,drunk}}}
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM