-1

I have a .txt file with 20 lines. Each line carrying 10 zeroes separated by comma.

0,0,0,0,0,0,0,0,0,0

I want to replace every fifth 0 with 1 in each line. I tried .replace function but I know there must be some easy way in python

njzk2
  • 38,969
  • 7
  • 69
  • 107
  • Is your expected output the corrected input text file, or something else? – Tim Biegeleisen Dec 13 '19 at 06:27
  • 4
    if you know that the file you want needs to contain 20 lines, each containing 4 zeroes, one 1, and 5 zeroes, then why do you need to replace anything? – njzk2 Dec 13 '19 at 06:27
  • I definitely don't have just 20 lines. Its a big file with huge number of lines, each line carrying huge number of zeroes separated by commas. In each line, I have to replace some zeroes at specific positions with 1. In question I asked for a smaller template, using the answers I can apply the code on a bigger file. @Tim I need the output as the corrected input text file. Thanks – Muhammad Qasim Dec 13 '19 at 06:40

2 Answers2

0

You can split the text string with the below command.

text_string="0,0,0,0,0,0,0,0,0,0"
string_list= text_string.split(",")

Then you can replace every fifth element in the list string_list using insert command.

for i in range(4,len(string_list),5):
    string_list.insert(i,"1")

After this join the elements of the list using join method

output = "".join([str(i)+"," for i in string_list])

The output for this will be :

'0,0,0,0,1,0,0,0,0,1,0,0,'

This is one way of doing

McLovin
  • 555
  • 8
  • 20
0

If text in this File follows some rule, you can parse it as CSV file, and change every fifth index and rewrite it to a new file.

But if you want to modify the existing text file, like replace the character then you can use seek refer to How to modify a text file?

eroot163pi
  • 1,791
  • 1
  • 11
  • 23