Vinit
Vinit

Reputation: 1

Reading multiline strings in a file

I am trying to read a file line by line. The file is a tcl file that contains various variable definitions. Some variable definitions are long and are spread across multiple lines : for example :

set ref_lib [list a b c d \
e\ 
f\
g\
]

Is there a way to consider this whole line as a single line? I am using readlines() function while parsing throgh line by line. My code looks like this

baseScript=open(sys.argv[1],"r")
count = 0
for line in baseScript.readlines():  
    print line  
baseScript.close()

But this considers multiline strings as different lines. Any help would be appreciated! :)

Upvotes: 0

Views: 482

Answers (1)

Mike67
Mike67

Reputation: 11342

You can loop through the file lines a concatenate the extended lines:

ss = r'''
set ref_lib [list a b c d \
e\ 
f\
g\
]
a = 123
set ref_lib [list c v b n \
e\
f\
g\
]
set ref_lib [list z a s d \
e\
f\
g\
]
'''.strip()

with open('test.dat','w') as f: f.write(ss)  # test file

#########################

outlines = []

with open('test.dat') as f:
   lines = f.readlines()

tmp = ''
for ln in lines:
   ln = ln.strip()   
   if ln.endswith('\\'): # partial line
       tmp += ln[:-1]
   else:  # end of line
       tmp += ln
       outlines.append(tmp)
       tmp = ''
print('\n'.join(outlines))   

Output

set ref_lib [list a b c d efg]
a = 123
set ref_lib [list c v b n efg]
set ref_lib [list z a s d efg]

Upvotes: 1

Related Questions