【发布时间】:2018-08-10 23:34:33
【问题描述】:
我有一组 csv 文件,我正试图在将它们放入数据库之前对其进行清理。这些文件用制表符划定,有两种格式。一种格式如下所示:
Some text string
Field1\tField2\tField3\tField4
Some text string 总是以相同的顺序开始,所以我想用它来识别需要修改的文件。从那里我可以删除前两行(第一行和接下来的空行)。
我已经能够成功地找到以这个字符串开头的文件,但我只能通过遍历每一行来做到这一点,这不是我想要做的最好的方法。
其中 csvFiles 是目录中 csv 文件的列表:
在 csv 模块中:
for csvFile in csvFiles:
with open(csvFile, newline='') as f:
for line in f:
if line.startswith("Some"):
print("Found it")
在熊猫中:
for csvFile in csvFiles:
standings = pandas.read_csv(csvFile, sep='/t', header=None, engine='python')
for row in standings:
if standings[row][0].startswith("Some"):
print("Found it")
我想简单地选择第一行并用 if 语句检查它,最好是在 pandas 中,但我没有成功。 pandas 将第一行解释为标题,并为每个后续行分配行索引,因此我无法按索引选择第一行。我已尝试设置header=None 以便为每一行编制索引,但仍无法按索引选择第一行。
我试图弄清楚如何遍历 csvFiles 列表中的文件,找到以 Some text string 开头的文件,然后仅从这些文件中删除前两行以及后面的一些行。
我理想的解决方案是这样开始的:
for csvFile in csvFiles:
standings = pandas.read_csv(csvFile, sep='/t', header=None, engine='python')
if standings[row][0].startswith("Some"):
print("Found it")
#do some stuff
【问题讨论】:
标签: python python-3.x pandas csv