如何在Python中选择并向标记文件添加条目?

2024-04-29 16:58:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个data.md文件,如下所示:

## intent:greet
- hey
- hello
- hi
- good morning
- good evening
- hey there

## intent:goodbye
- bye
- goodbye
- see you around
- see you later

## intent:affirm
- yes
- indeed
- of course
- that sounds good
- correct

## intent:deny
- no
- never
- I don't think so
- don't like that
- no way
- not really

现在我想添加一个新的例子yes, I affirm## intent:affirm,如下所示:

## intent:affirm
- yes
- indeed
- of course
- that sounds good
- correct
- yes, I affirm

如何在Python中实现这一点?你知道吗

目前,我不知道从什么开始,因为我是Python新手,所以除了在网上搜索相关文章之外,在这里寻求帮助之前,我还没有做任何具体的工作。你知道吗


Tags: ofnoyouthatyesgoodseeindeed
2条回答

您必须重写文件,如果您仍然可以访问,请使用“复制/粘贴”并在新文件中插入复制的文件和要添加的部分。你不能改变它,因为它是一个操作系统的东西,而不是python。您可以使用操作系统中的终端或命令行替换该文件。你知道吗

窗口:

REPLACE [Drive:][path]SourceFiles [Drive:][path2] [/A] [/P] [/R] [/W]其中:

/A是任何丢失的文件

/P提示确认

/R是只读文件

/W是等待/暂停(最初用于软盘)

Linux操作系统:

在tmp文件夹中创建并保存新文件,然后在终端中:

cat /tmp/new-file | sudo tee /home/user/(insert more folders and file if needed)

苹果操作系统/Mac:

我不知道如何做到这一点,因为我从来没有一个mac,但谷歌或可能在StackExchange的一些社区。你知道吗

这比看起来要困难一些,因为不能用python编辑一个文件(除非它在末尾)。因此,可以先将文件读入数组,然后重新写入。例如:

# Load the file into file_content
file_content = [ line for line in open('data.md') ]

# Overwrite it
writer = open('data.md','w')

for line in file_content:
    # We search for the correct section
    if line.startswith("##"):
        section = line.strip()

    # Re-write the file at each iteration
    writer.write(line)

    # Once we arrive at the correct position, write the new entry
    if section == "## intent:affirm" and line.strip() == "- correct":
        writer.write("- yes, I affirm\n")

writer.close()

相关问题 更多 >