擅长:python、mysql、java
<p>解析写入文本文件的表最方便的方法是使用<a href="http://docs.python.org/library/csv.html" rel="nofollow noreferrer">csv module</a>。它支持任何分隔符,使用起来比手动逐行解析更方便。示例:</p>
<pre><code>import csv
def get_first_and_last_column(filename, separator):
with file(filename, 'rb') as file_obj:
for line in csv.reader(file_obj,
delimiter=separator, # Your custom delimiter.
skipinitialspace=True): # Strips whitespace after delimiter.
if line: # Make sure there's at least one entry.
yield line[0], line[-1]
if __name__ == '__main__':
for pair in get_first_and_last_column(r'c:\temp\file.txt', ';'):
print pair
</code></pre>
<p>现在,如果你给它一个这样的文件:</p>
<pre><code>Edgar; Alan; Poe
John; Smith
Lots; of; whitespace; here
</code></pre>
<p>它将产生以下输出:</p>
<pre><code>('Edgar', 'Poe')
('John', 'Smith')
('Lots', 'here')
</code></pre>
<p><strong>编辑</strong>:到<code>csv.reader</code>的自定义参数也可以作为关键字参数传递(谢谢,nosklo!)。</p>