Search code examples
pythonfileline

How to switch the order of text in a line?


I have a text file with lines going like this: text1:numbers:text2. How do I separate these so that I can output for example text1:text2:numbers to another file?

file1=open("textfile.txt","r")

file2=open("textfile2.txt","w") 

while True:

    line=file1.readline()

    a=line.split(":")

    if line=="":break

Solution

  • you can assign each text part to a variable in your split, then write out in the separate order.

    with open("textfile.txt") as f1, open("textfile2.txt", "w") as f2:
        for line in f1:
            text1, numbers, text2 = line.split(":")
            # N.B. this will fail if there are more *or* less than 3 parts to line.split(":")
            # on any line of the file. Ensure that there is not, or wrap this in a
            # try/except block and handle appropriately.
    
            f2.write("{}:{}:{}\n".format(text1, text2, numbers))
            # or f2.write(':'.join([text1, text2, numbers, "\n"]))
            # or f2.write(text1 + ":" + text2 + ":" + numbers + "\n")
            # or any other way to assemble the text you want.
    
            # my favorite in Py3.6+ is an f-string
            # f2.write(f"{text1}:{text2}:{numbers}\n")
    

    Note that I'm also using a context manager to open the files, and iterating over the file objects directly rather than an infinite loop until readline returns nothing. You should prefer context managers over explicit open and close statements because it ensures the file object/s close after exiting from the block, even if that exit isn't clean (exceptions are thrown and handled or etc). Iterating over the file object instead of reading a line at a time in an infinite loop is just idiomatically nicer-looking.