Search code examples
pythonlistfileswap

Comprehension List and new File


Example of two text files. The left image is before, the right one is after

I need to swap the dates in one file and put it on a new file using comprehension lists. How would I do that? This is what I have:

list1 = [x.replace("\n","").replace("/"," ").split(" ") for x in open("dobA.txt")]
list2 = [(i[len(i)-2],i[len(i)-3]) for i in list1]
with open("dobB.txt", "w") as newfile:
        newfile.write()

The top line of code makes the dates into their own string, such as "10".

The second line of code swaps the numbers I need but only prints out: [('11', '10'), ('8', '9'), ('9', '7')]

The last two are just writing a new file.

How would I swap these two numbers and put them on a new file? Thank you.


Solution

  • First of all, do this:

    i[-2]
    

    instead of

    i[len(i)-2]
    

    There are a couple of options to approach this:

    Readable one without comprehensions:

    with open("old_file.txt") as old_file, open("new_file.txt", "w") as new_file:
        for line in old_file:
            name, surname, date = line.split()
            day, month, year = date.split("/")
            print(f"{name} {surname} {month}/{day}/{year}", file=new_file)
    

    Regex replace:

    import re
    from pathlib import Path
    
    text = Path("old_file.txt").read_text()
    replaced = re.sub(r"(\d+)/(\d+)/(\d+)", r"\2/\1/\3", text)
    Path("new_file.txt").write_text(replaced)
    

    If you really need comprehensions:

    with open("old_file.txt") as old_file, open("new_file.txt", "w") as new_file:
        new_lines = [
            f"{text} {date.split('/')[1]}/{date.split('/')[0]}/{date.split('/')[2]}"
            for text, date in [line.rsplit(maxsplit=1) for line in old_file]
        ]
        print("\n".join(new_lines), file=new_file)