我刚刚开始编写代码,我正在尝试从项目的CSV中删除某些列,我们不应该使用pandas。例如,我必须删除的一个字段名为DwTm
,但是我必须删除大约15列;我只需要前几个,下面是我得到的:
import csv
FTemp = "D:/tempfile.csv"
FOut = "D:/NewFile.csv"
with open(FTemp, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
with open(FOut, 'w') as new_file:
fieldnames = ['Stn_Name', 'Lat', 'Long', 'Prov', 'Tm']
csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames)
for line in csv_reader:
del line['DwTm']
csv_writer.writerow(line)
当我运行这个,我得到的错误
del line['DwTm']
TypeError: list indices must be integers or slices, not str
这是我发现的唯一一种不用熊猫的方法。有什么想法吗?你知道吗
最简单的方法是使用DictReader读取文件。与用于编写文件的DictWriter一样,DictReader对行使用字典,因此从旧行中删除键然后写入新文件的方法将按预期工作。你知道吗
可以同时打开要读取的文件和要写入的文件。假设您知道要保留的列的索引,例如0、2和4:
列表理解(数据)只从每一行中提取要保留的列,并使用join方法(加上为每一新行添加一个结束行)立即逐行写入新文件。你知道吗
如果您只知道要保留/删除的字段的名称,则需要从csv文件的第一行提取索引,但这并不困难。你知道吗
下面
你知道吗示例.csv你知道吗
示例_输出.csv你知道吗
相关问题 更多 >
编程相关推荐