首页  >  文章  >  后端开发  >  python 文件字符串转列表时遇空行的解决办法!

python 文件字符串转列表时遇空行的解决办法!

PHP中文网
PHP中文网原创
2017-07-08 18:13:181832浏览

文件内容如下:

Alex <span style="color: #800080">100000</span><span style="color: #000000">
Rain </span><span style="color: #800080">80000</span><span style="color: #000000">
Egon </span><span style="color: #800080">50000</span><span style="color: #000000">
Yuan </span><span style="color: #800080">30000</span><span style="color: #000000">
                #此处有一个空行!</span>

现在看如何处理并转成列表!

salary_info = open(<span style="color: #800000">"</span><span style="color: #800000">salaryinfo.txt</span><span style="color: #800000">"</span>, <span style="color: #800000">"</span><span style="color: #800000">r+</span><span style="color: #800000">"</span>, encoding=<span style="color: #800000">"</span><span style="color: #800000">UTF-8</span><span style="color: #800000">"</span><span style="color: #000000">)
salary_info_list </span>=<span style="color: #000000"> []
</span><span style="color: #0000ff">for</span> line <span style="color: #0000ff">in</span><span style="color: #000000"> salary_info.readlines():
    </span><span style="color: #0000ff">if</span> line == <span style="color: #800000">'</span><span style="color: #800000">\n</span><span style="color: #800000">'</span><span style="color: #000000">:
       pass
    </span><span style="color: #0000ff">else</span><span style="color: #000000">:
       salary_info_list.append(list(line.split()))  # 读到的列表以追加的方式追加到salary_list值中。</span>

输出结果如下:

[[<span style="color: #800000">'</span><span style="color: #800000">Alex</span><span style="color: #800000">'</span>, <span style="color: #800000">'</span><span style="color: #800000">100000</span><span style="color: #800000">'</span>], [<span style="color: #800000">'</span><span style="color: #800000">Rain</span><span style="color: #800000">'</span>, <span style="color: #800000">'</span><span style="color: #800000">80000</span><span style="color: #800000">'</span>], [<span style="color: #800000">'</span><span style="color: #800000">Egon</span><span style="color: #800000">'</span>, <span style="color: #800000">'</span><span style="color: #800000">50000</span><span style="color: #800000">'</span>], [<span style="color: #800000">'</span><span style="color: #800000">Yuan</span><span style="color: #800000">'</span>, <span style="color: #800000">'</span><span style="color: #800000">30000</span><span style="color: #800000">'</span>]]

 

以上是python 文件字符串转列表时遇空行的解决办法!的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn