文件內容如下:
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中文網其他相關文章!