问题:
在 Python 中,正在处理 CSV 文件,但第一行(标题行)正在被修改而不是被排除。
有问题的代码:
<code class="python">in_file = open("tmob_notcleaned.csv", "rb") reader = csv.reader(in_file) out_file = open("tmob_cleaned.csv", "wb") writer = csv.writer(out_file) row = 1 for row in reader: # Row processing logic in_file.close() out_file.close()</code>
问题:
将 'row' 变量初始化为 1 不会阻止处理标题行。
解决方案:
要跳过标题行,请使用next() 函数将读取器推进一项可迭代。这种情况下,next()的返回值可以被忽略。
修改代码:
<code class="python">with open("tmob_notcleaned.csv", "rb") as in_file, open("tmob_cleaned.csv", "wb") as out_file: reader = csv.reader(in_file) next(reader, None) # Skip the header row writer = csv.writer(out_file) for row in reader: # Row processing logic</code>
替代选项:
如果输出文件中需要标题行,可以在循环之前将其传递给 writer.writerow():
<code class="python">with open("tmob_notcleaned.csv", "rb") as in_file, open("tmob_cleaned.csv", "wb") as out_file: reader = csv.reader(in_file) headers = next(reader, None) # Returns the header row or None if the input is empty if headers: writer.writerow(headers) for row in reader: # Row processing logic</code>
以上是为什么我的 Python 代码处理 CSV 文件中的标题行而不是跳过它?的详细内容。更多信息请关注PHP中文网其他相关文章!