Ank
Ank

Reputation: 6270

join lines in a text file python

This is really basic but for some reason I am struggling with it

I have a file f.txt that has the following contents

abc
def
ghi
jkl

I want the output to be "abc"OR"def"OR"ghi"OR"jkl" This is what I have tried

join = ""
with open("f.txt") as f:
 for line in f:
   join = "\""+line.rstrip()+"OR\""+join
f.close()
print join[:-2]

Upvotes: 1

Views: 1158

Answers (3)

Jeffrey4l
Jeffrey4l

Reputation: 121

Try following code.

with open('f.txt') as f:
   print 'OR'.join(['\"%s\"' % line[:-1] for line in f])

Upvotes: 0

Hugh Bothwell
Hugh Bothwell

Reputation: 56634

with open("f.txt") as inf:
    items = ('"{}"'.format(line.strip()) for line in inf)
    join = "OR".join(items)

Upvotes: 2

Joran Beasley
Joran Beasley

Reputation: 113940

with ... as f:
   " or ".join(f.read().split())

if your input is really as simple as you show

Upvotes: 6

Related Questions