Fakhrizal Masduki Fakhrizal Masduki - 20 days ago 6
Python Question

How to append characters between two strings in existing .txt file using python

I am trying to add "," between a lot of data in .txt file and I also want to delete the second rows.

This is example of my txt file

1 1 139 178 128 83 140 140 87 87
2 1 199 204 130 111 198 198 89 89
3 1 188 182 107 120 183 183 109 109
......


'....' here means thousand of data.

and I want to print the result in a new .txt file

This is the results I wanted.

1, 139, 178, 128, 83, 140, 140, 87, 87
2, 199, 204, 130, 111, 198, 198, 89, 89
3, 188, 182, 107, 120, 183, 183, 109, 109
.....


I really hope some one here can help me with this problem and I appreciate your help very much!

Thanks!

Answer

First, iterate over the lines:

with open(filename) as f:
  for line in f:
    # can process the line here

Now lets see what we can do with each line:

words = line.split() # split on whitespace
del words[1] # remove the word at index 1
joined = ", ".join(words)
print(joined) # can print to stdout, or write to another file
Comments