<pre><code>import csv
def filter_dates(csv_filepath)
with open(csv_filepath, 'r') as in_file:
csv_in = list(csv.reader(in_file))
# create accumulator for new list to add only valid values
filtered_list = []
filetered_list.append(csv_in[0]) # append header to new list
# filter the list making sure no errors appear BEFORE writing to the file
for row in csv_in[1:]: #skip header (first row)
if int(row[2]) >= 2011: # if entry is NEWER OR EQUAL TO than 7 years, we add it to filtered_list
filtered_list.append(row)
# now filtered_list contains only entires where index position 2 contains valid years
with open(csv_filepath, 'w') as out_file:
writer = csv.writer(out_file)
writer.writerows
</code></pre>
<p>下面是一个完全独立的例子:</p>
^{pr2}$
<p>注意:</p>
<ul>
<li>通常,在打开要写入的文件(在本例中是覆盖)之前,最好将这类内容存储在内存中,这样在读取和过滤文件时出现的任何错误都会在我们试图修改输出之前发生</li>
<li>覆盖一个文件最简单的方法是首先读取它,将内容提交到内存中(<code>csv_in</code>我在第一个<code>with</code>块中定义的数组),然后*最后8一旦数据准备就绪(<code>filtered_list</code>)提交到一个文件</li>
<li>永远不要在python中使用<code>global</code>声明,这是不值得的,并且会引起很多麻烦</li>
</ul>
<p>试验</p>