I would like to add a comma into my .txt
file using Python.
with open('filename.txt', 'r') as f:
fileText = f.read()
filedata = fileText.split('\n')
The above code would read the file and split it by newline.
Text file is something like this:
ABC name1, name2, name3
XYZ nameA, [nameBa nameBb], nameC
I need to add a comma after the first string only. The file contains 4 or 5 strings; most of them are separated by comma except the first one.
I have used two for
loops to work out the same, but I am thinking it would be better if I could write into my text file using Python and insert only the comma then I will only have to use one loop to get all of the strings.
Expected result:
ABC, name1, name2, name3
XYZ, nameA, [nameBa nameBb], nameC
I am using list
structure but dict
might be better as I can use the first string as key (ABC
, XYZ
) and store the rest in either values or as a list made up of all the other strings.
Can anyone help me with inserting the comma into my text file at a specific location (i.e. fourth character from the left on every line)?