1

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

aaron
  • 39,695
  • 6
  • 46
  • 102
naveed
  • 11
  • 1
  • 3
  • You have a list of strings in `filedata` right? Why don't you loop through this list and `split()` each string by a ` ` character, then the first item of the corresponding list will be `["ABC", "name1", ..]` and then `join()` the required items using `,` – Sudheesh Singanamalla Nov 18 '17 at 15:27
  • Thanks. Split() each string by a separator doesn't give me same result i.e. ["ABC", "name1", ..] instead I get ABC name1, name2.. – naveed Nov 18 '17 at 16:22

3 Answers3

1

You can build such a dict like this:

d = {}
with open('filename.txt', 'r') as f:
    for line in f:
        k, v = line.split(' ', 1)
        d[k.strip()] = [s.strip() for s in v.split(',')]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Thanks. Using above code, I get dict key with first string and second i.e. {'ABC\tname1,': [name2 name3] etc. etc. I have coded in few more lines using simple for loop such that first string(ABC) as dictionary key and I have split records for each line but I only managed to do it with first two stings as they are separated by \t and rest of stings by commas. – naveed Nov 18 '17 at 16:48
0
with open(file, 'r+') as file

the +r will append to the line. Check out this question its basically the same: Python insert characters into txt file without overwrite

700L
  • 86
  • 1
  • 4
  • I have used r, a, w etc. but i am trying to figure out a way to go into text file exact location i.e. 4th character of each line and then append comma there. would that be a byte location? – naveed Nov 18 '17 at 16:51
0

As you said your main goal is :

I can use the first string as key (ABC, XYZ) and store rest in either values or as a list made up of all the other strings.

You can use regex here , And you can get result without adding comma:

import re
pattern=r'(^\w+)\s.(\w.+)'
final_dict={}
with open('file.txt','r') as f:
    for line in f:
        match=re.finditer(pattern,line)

        for find in match:
            final_dict[find.group(1)]=[find.group(2)]

print(final_dict)

output:

{'XYZ': ['nameA, [nameBa nameBb], nameC'], 'ABC': ['name1, name2, name3']}
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
  • Thanks. for some reason I was getting unwanted truncation on values i.e {'XYZ': ['ameA, nameB'], 'ABC' : ['ameD, nameE'] etc. I deleted the first . from pattern and it shows the full value without truncation. ta – naveed Nov 18 '17 at 17:50
  • @naveed if my solution helped you can accept the answer :) – Aaditya Ura Nov 18 '17 at 17:56