Stack Overflow Solution: Comprehension List and new File

Stack Overflow solution

In [69]:
from pathlib import Path
import tempfile
from datetime import datetime
import operator as op
In [70]:
_, filename = tempfile.mkstemp()
file_A = Path(filename)
_, filename = tempfile.mkstemp()
file_B = Path(filename)
In [71]:
contents_A = """Adam Brown 10/11/1999
Lauren Marie Smith 9/8/2001
Vincent Guth II 7/9/1980"""
fileA.write_text(contents_A)
Out[71]:
74

Without the assignment operator.

In [72]:
file_B.write_text("\n".join([
    " ".join(
        op.add(
            line.split()[:-1],
            [
                datetime.strptime(
                    line.split()[-1], "%m/%d/%Y",
                ).strftime("%-d/%-m/%Y",),
            ],
        )
    )
    for line in fileA.read_text().splitlines()
]))
Out[72]:
74

With the assignment operator.

In [73]:
file_B.write_text(
    "\n".join( # re-join the lines
        [
            " ".join( # re-join the words
                (
                    # Store the split line into words. Then slice all but last.
                    " ".join((words := line.split())[:-1]),
                    # Convert the last word to desired date format.
                    datetime.strptime(words[-1], "%m/%d/%Y",).strftime("%-d/%-m/%Y",),
                )
            )
            for line in fileA.read_text().splitlines()
        ]
    )
)
Out[73]:
74
In [74]:
print(file_B.read_text())
Adam Brown 11/10/1999
Lauren Marie Smith 8/9/2001
Vincent Guth II 9/7/1980