Reputation: 3161
I have a data.md
file as follows:
## 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
Now I want to add a new example yes, I affirm
to ## intent:affirm
so that it becomes as follows:
## intent:affirm
- yes
- indeed
- of course
- that sounds good
- correct
- yes, I affirm
How to achieve this in Python?
Currently, I have no idea on what to start with as I am new to Python, so haven't done anything concrete before seeking help here other than search online for related articles.
Upvotes: 1
Views: 3015
Reputation: 197
You will have to rewrite the file, if you can still access, use copy/paste and in the new file insert the copied file and the parts you want to add. You can't change it because it is a os thing, not python. You may be able to replace the file using the terminal or command line in your OS.
Windows:
REPLACE [Drive:][path]SourceFiles [Drive:][path2] [/A] [/P] [/R] [/W]
where:
/A
is any missing files
/P
is prompt for confirmation
/R
is replace even read-only file
/W
is wait/pause (originally used for floppy disks)
Linux:
Create and save the new file in the tmp folder, then in the terminal:
cat /tmp/new-file | sudo tee /home/user/(insert more folders and file if needed)
OS X/Mac:
I am unsure how to do this as I have never had a mac, but Google or maybe some communities in StackExchange.
Upvotes: 0
Reputation: 1514
It's a bit more difficult than it seems since you can't just edit a file in python (unless it's at the end). So you can first read the file into an array, and then re-write it. For example:
# 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()
Upvotes: 3