I currently have a text file that reads like this:
101, Liberia, Monrovia, 111000, 3200000, Africa, English, Liberia Dollar;
102, Uganda, Kampala, 236000, 34000000, Africa, English and Swahili, Ugandan Shilling;
103, Madagascar, Antananarivo, 587000, 21000000, Africa, Magalasy and Frances, Malagasy Ariary;
I'm currently printing the file using this code:
with open ("base.txt",'r') as f:
for line in f:
words = line.split(';')
for word in words:
print (word)
What I would like to know is, how can I modify a line by using their id number (101 for example) and keep the format they have and add or remove lines based on their id number?
My understanding your asking how to modify a word in a line and then insert the modified line back into the file.
Change a word in the file
In order to use this function to set
line 3, word 2
toNot_Madasgascar
call it like this:You will always have to add
1
to the line/word number because the first line/word is0
Add a new line to the file
In order to use this function add a line at the end containing the words
this
line
is
at
the
end
call it like this:For more information on opening files see here.
For more information on reading from and modifying files see here.
pandas
is a strong tool for solving your requirements. It provides the tools for easily working with CSV files. You can manage your data inDataFrames
.Reading this file into an
OrderedDict
would probably be helpful if you are trying to preserve the original file ordering as well as have the ability to references lines in the file for modification/addition/deletion. There are quite a few assumptions about the full format of the file in the following example, but it will work for your test case: