Stormvirux
Stormvirux

Reputation: 909

Modifying file content using python

I have a file that consists of a single line:

a,x,b,c,d,e 

I want to convert this into

a,x,b,x,c,x,d,x,e,x

Is there any easy way to achieve this with python?

Upvotes: 1

Views: 71

Answers (2)

U2EF1
U2EF1

Reputation: 13289

import re
s = open(filename).read()
open(filename, 'w').write(',x,'.join(re.findall(r'[a-wyz]', s)) + ',x\n')

Upvotes: 1

MONTYHS
MONTYHS

Reputation: 924

 my_file = open(filename)
 data = my_file.read()
 data = data.split(',')
 str = ''
 for each in data:
     if each != 'x':
         str += each + ',' + 'x' + ','
 str= str.strip(',')
 print str

Upvotes: 1

Related Questions