简体   繁体   English

读取文件中的多行字符串

[英]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.该文件是一个包含各种变量定义的 tcl 文件。 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.我在逐行解析 throgh 时使用 readlines() 函数。 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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