首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Python 2读取CSV文件

使用Python 2读取CSV文件
EN

Stack Overflow用户
提问于 2013-06-12 23:57:10
回答 2查看 1.2K关注 0票数 0

我运行的是Python 2.7。我对Python非常陌生。我正在尝试读取一个CSV文件(值由空格分隔),并根据坐标上方的头部分隔其中的值。文件的格式不是我习惯的格式,并且我在获取正确读取的值时遇到了问题。即使我可以让他们正确地阅读,我也不知道如何将他们放在一个列表中。

下面是CSV文件的外观:

代码语言:javascript
复制
# image name
1.png
# probe locations
100 100
200 100
100 200
300 300

# another image name
2.png
100 200
200 100
300 300
135 322

# end

下面是我正在使用的代码:

代码语言:javascript
复制
class CommentedFile:
    def __init__(self, f, commentstring="#"):
        self.f = f
        self.commentstring = commentstring
    def next(self):
        line = self.f.next()
        while line.startswith(self.commentstring):
            line = self.f.next()
        return line
    def __iter__(self):
        return self

#I did this in order to ignore the comments in the CSV file

tsv_file = csv.reader(CommentedFile(open("test.exp", "rb")),
                  delimiter=' ')


for row in tsv_file:
    if row != int:
        next(tsv_file)
    if row:
        print row

代码打印出来:

代码语言:javascript
复制
['100', '100']
['100', '200']
['100', '200']
['300', '300']
Traceback (most recent call last):
  File "the path", line 57, in <module>
next(tsv_file)
StopIteration

所以我试着让程序根据头部来分离坐标,然后把它们放到不同的列表中。谢谢你的帮助!

EN

回答 2

Stack Overflow用户

发布于 2013-06-13 00:11:46

看看pandas吧。它有一个DataFrame对象,可以保存你的数据并允许你以一种直观的方式进行操作。它还有一个read_csv函数,在处理csv文件时省去了很多麻烦。

例如:

代码语言:javascript
复制
import pandas as pd

#reads your csv file in and returns a DataFrame object as metioned above. 
df = pd.read_csv("your_csv.csv", sep=' ', names=['co_a','co_b'], header=None, skiprows=2)

#extracts your discordant to separate lists
list1 = df.co_a.to_list()
list2 = df.co_b.to_list()

您可以使用dfdf.head()查看数据框架以及数据是如何管理的。值得一提的是,df.co_a是一个Series对象,想象一下超级列表/字典,您可能可以从那里进行分析或操作。

另外,如果您向我展示csv文件中的注释是如何存在的,那么我可以向您展示如何使用read_csv忽略它们。

我知道您正在寻找csv module的答案,但这是一个更高级的工具,从长远来看可能会对您有所帮助。

希望它能帮上忙!

票数 0
EN

Stack Overflow用户

发布于 2013-06-13 00:14:21

实际上,你的代码对我来说运行得很好。我不知道你为什么要追查。

tmp.csv

代码语言:javascript
复制
# image name
1.png
# probe locations
100 100
200 100
100 200
300 300

# another image name
2.png
100 200
200 100
300 300
135 322

# end

tmp.py

代码语言:javascript
复制
import csv

class CommentedFile:
    def __init__(self, f, commentstring="#"):
        self.f = f
        self.commentstring = commentstring
    def next(self):
        line = self.f.next()
        while line.startswith(self.commentstring):
            line = self.f.next()
        return line
    def __iter__(self):
        return self

#I did this in order to ignore the comments in the CSV file

tsv_file = csv.reader(CommentedFile(open("tmp.csv", "rb")),
                  delimiter=' ')


for row in tsv_file:
    if row != int:
        next(tsv_file)
    if row:
        print row

Shell输出

代码语言:javascript
复制
tmp$python tmp.py 
['1.png']
['200', '100']
['300', '300']
['2.png']
['200', '100']
['135', '322']
tmp$uname -mprsv
Darwin 12.4.0 Darwin Kernel Version 12.4.0: Wed May  1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 i386
tmp$python --version
Python 2.7.2
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17070071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档