2016-07-04 64 views
0

我有一本字典:如何在文本文件中缩进整个文本字符串?

page_info = {'LISTS':['string 1', 'string 2']} 

我想打印的字的文本文件“列表”为标题,并出现在它下面的键值和缩进一个格的权利。

with codecs.open(stats_file, 'a', encoding="utf8") as file: 
    file.write('LISTS:' + '\n') 
    for tag in page_info['LISTS']: 
     file.write('\t' + tag + '\n\n') 

下面是输出到文件: enter image description here

正如你看到的,只有第一行缩进每串。我将如何缩进字符串的整个文本块?

+0

你需要将每个字符串拆分成自己的行,并缩进每个字符串。由于你只处理整个字符串,所以你从不做任何关于内部换行符的事情,只有第一行。 –

回答

2

使用textwrap module来包装你行,并增加缩进到每一行:

wrapper = textwrap.TextWrapper(initial_indent='\t', subsequent_indent='\t') 
for tag in page_info['LISTS']: 
    wrapped = wrapper.fill(tag) 
    file.write(wrapped + '\n') 

你可能想太多指定width参数;默认设置为70个字符。