擅长:python、mysql、java
<p>您可以使用<code>ast.literal_eval</code>(<a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer">doc</a>)从文本文件加载数据。你知道吗</p>
<p>对于输入文件<code>file.txt</code>的内容:</p>
<pre><code>{'a':'1','b':'2','c':'3'}
{'a':'4','b':'5','c':'6'}
{'a':'7','b':'8','c':'9'}
{'a':'10','b':'11','c':'12'}
{'a':'x','b':'y','c':'z'}
</code></pre>
<p>您可以使用此脚本加载数据并输入<code>file.csv</code>:</p>
<pre><code>import csv
from ast import literal_eval
with open('file.txt', 'r') as f_in:
lst = [literal_eval(line) for line in f_in if line.strip()]
with open('file.csv', 'w', newline='') as csvfile:
fieldnames = ['a', 'b', 'c']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(lst)
</code></pre>
<p><code>file.csv</code>将变成:</p>
<pre><code>a,b,c
1,2,3
4,5,6
7,8,9
10,11,12
x,y,z
</code></pre>
<p>将文件导入LibreOffice:</p>
<p><a href="https://i.stack.imgur.com/x6ew5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x6ew5.png" alt="enter image description here"/></a></p>