Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 理解列表和新文件_Python_List_File_Swap - Fatal编程技术网

Python 理解列表和新文件

Python 理解列表和新文件,python,list,file,swap,Python,List,File,Swap,我需要交换一个文件中的日期,并使用理解列表将其放在一个新文件中。我该怎么做?这就是我所拥有的: 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() 代码的顶

我需要交换一个文件中的日期,并使用理解列表将其放在一个新文件中。我该怎么做?这就是我所拥有的:

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()
代码的顶行将日期转换为自己的字符串,如“10”

第二行代码交换我需要的数字,但只打印出来: [('11','10'),('8','9'),('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)
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)
正则表达式替换:

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, 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)
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)

我想看看这是否可以一次性完成。它可能会挑战“可读性”

翻转月份和日期的最简单方法是利用on datetime对象

有关格式设置选项,请参见

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年10月11日

劳伦·玛丽·史密斯8/9/2001

文森特·古思二世1980年9月7日

如果没有“:=”操作符,问题会稍微多一些。这意味着在理解过程中必须调用
line.split()
两次

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()
]))

print(file_B.read_text())
输出:

亚当·布朗1999年10月11日

劳伦·玛丽·史密斯8/9/2001

文森特·古思二世1980年9月7日


抱歉,伙计,这太复杂了,应该用5行代码来完成。但是你选择编写理解,重点是使用日期时间字符串格式。我修复了格式。为什么任意5行代码?我是在一个表达中这样做的。评论不是为了进一步讨论;这段对话已经结束。