[英]Delete first rows of csv file in python
我们要删除 csv 文件的前 34 行,因为它是无用的文本标题,这是没有用的。
我们在 Python 3 中使用以下代码行:
with open("test.csv",'r') as f, open("temp.csv",'w') as f1:
next(f) # skip header line
for line in f:
f1.write(line)
上面应该只“删除”第一行,但我们想象我们可以在 next(f) 周围创建一个范围为 (0, 35) 的 for 循环。
我们的 csv 数据在 test.csv 中,我们有一个名为 temp.csv 的空 csv 文件。 上面的代码应该跳过 test.csv 的第一行,然后将其余部分复制到 temp.csv 中。
不幸的是,我们收到此错误:
Traceback (most recent call last):
File "delete.py", line 2, in <module>
next(f) # skip header line
File "/usr/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf8 in position 2625: invalid start byte
为什么会出现这种情况? 删除 csv 文件中前 34 行的 pythonical 方法是什么?
我知道您想在打开和读取 CSV 文件时使用with
上下文管理器跳过行with
但我建议您使用一个名为pandas的优秀库来读取和跳过 CSV 文件中的行,如下所示,您也可以将其保存到另一个很容易从df数据框中获取 .csv 文件
import pandas as pd
#skiprows=34 will skip the first 34 lines and try to read from 35 line
df = pandas.read_csv('my_csv_file.csv', skiprows=34)
#print the data frame
df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.