Read specific columns in csv using python

前端 未结 7 1369
耶瑟儿~
耶瑟儿~ 2021-02-06 06:27

I have a csv file that look like this:

+-----+-----+-----+-----+-----+-----+-----+-----+
| AAA | bbb | ccc | DDD | eee | FFF | GGG | hhh |
+-----+-----+-----+-----+---         


        
7条回答
  •  失恋的感觉
    2021-02-06 07:12

    Context: For this type of work you should use the amazing python petl library. That will save you a lot of work and potential frustration from doing things 'manually' with the standard csv module. AFAIK, the only people who still use the csv module are those who have not yet discovered better tools for working with tabular data (pandas, petl, etc.), which is fine, but if you plan to work with a lot of data in your career from various strange sources, learning something like petl is one of the best investments you can make. To get started should only take 30 minutes after you've done pip install petl. The documentation is excellent.

    Answer: Let's say you have the first table in a csv file (you can also load directly from the database using petl). Then you would simply load it and do the following.

    from petl import fromcsv, look, cut, tocsv    
    
        #Load the table
        table1 = fromcsv('table1.csv')
        # Alter the colums
        table2 = cut(table1, 'Song_Name','Artist_ID')
        #have a quick look to make sure things are ok.  Prints a nicely formatted table to your console
        print look(table2)
        # Save to new file
        tocsv(table2, 'new.csv')
    

提交回复
热议问题