简体   繁体   English

读取 csv 文件并想跳过前两列

[英]Reading csv file and want to skip first two columns

I am trying to read a CSV file in Python.我正在尝试用 Python 读取 CSV 文件。 Further I want to read my whole file but just don't want first two columns.此外,我想阅读我的整个文件,但不想要前两列。 Also I don't have columns name so that I can easily drop or skip it.此外,我没有列名,因此我可以轻松删除或跳过它。

What code do I need to read the file without reading first two columns?我需要什么代码才能在不阅读前两列的情况下阅读文件?

I have tried below code:我试过下面的代码:

with open("data2.csv", "r") as file:
    lines = [line.split() for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))

I am just reading file line by line from above code.我只是从上面的代码中逐行读取文件。 But how to skip first two columns and then read the file?但是如何跳过前两列然后读取文件? I don't have names of the columns.我没有列的名称。

You should use the csv module in the standard library.您应该使用标准库中的csv模块。 You might need to pass additional kwargs (keyword arguments) depending on the format of your csv file.根据 csv 文件的格式,您可能需要传递额外的kwargs (关键字参数)。

import csv

with open('my_csv_file', 'r') as fin:
    reader = csv.reader(fin)
    for line in reader:
        print(line[2:])
        # do something with rest of columns...

if the lines list does getting the data you want you can use slicing to get rid of the columns you don't want:如果行列表确实获得了您想要的数据,您可以使用切片来摆脱您不想要的列:

getting rid of first two: lines[2:]摆脱前两个: lines[2:]

getting rid of last two: lines[:-2]去掉最后两个: lines[:-2]

with open("data2.csv", "r") as file:
    lines = [line.split()[2:] for line in file]
    for i, x in enumerate(lines):
        print("line {0} = {1}".format(i,x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM