我想看看是否可以一次完成。它可能会违抗“可读性”。
翻转月份和日期的最简单方法是在日期时间对象上利用string formatting methods。
有关格式化选项,请参见Python strftime reference。
from pathlib import Path
import tempfile
from datetime import datetime
import operator as op
# Create temporary files for reading and writing.
_,filename = tempfile.mkstemp()
file_A = Path(filename)
_,filename = tempfile.mkstemp()
file_B = Path(filename)
contents_A = """Adam Brown 10/11/1999
Lauren Marie Smith 9/8/2001
Vincent Guth II 7/9/1980"""
file_A.write_text(contents_A)
# This version requires Python 3.8.
# It uses the newly introduced assignment expression ":=".
# datetime objects have string formatting methods.
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()
]
)
)
print(file_B.read_text())
输出:
亚当·布朗1999年11月10日
Lauren Marie Smith 8/9/2001
Vincent Guth II,1980年9月7日
如果没有“:=”运算符,则会有更多问题。这意味着必须在理解中调用两次line.split()
。
file_B.write_text("\n".join([
" ".join(
op.add(
line.split()[:-1],[
datetime.strptime(
line.split()[-1],],)
)
for line in fileA.read_text().splitlines()
]))
print(file_B.read_text())
输出:
亚当·布朗1999年11月10日
Lauren Marie Smith 8/9/2001
Vincent Guth II,1980年9月7日
,
首先,请执行以下操作:
i[-2]
代替
i[len(i)-2]
有两种方法可以解决此问题:
可读而无须理解:
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)
正则表达式替换:
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)
如果您真的需要理解:
with open("old_file.txt") as old_file,"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)
本文链接:https://www.f2er.com/3089322.html