简体   繁体   中英

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! :)

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM