【问题标题】:Reading a CSV file using Python 2使用 Python 2 读取 CSV 文件
【发布时间】:2013-06-12 15:57:10
【问题描述】:

我正在运行 Python 2.7。我对 Python 很陌生。我正在尝试读取 CSV 文件(值由空格分隔)并根据坐标上方的标题分隔内部的值。文件的格式不是我习惯的格式,我无法正确读取这些值。即使我可以让它们正确阅读,我也不明白如何将它们放入列表中。

这是 CSV 文件的样子:

# 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

这是我正在使用的代码:

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

代码打印出来:

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

所以我试图让程序根据标题分隔坐标,然后将它们放入单独的列表中。感谢您的帮助!

【问题讨论】:

  • 那不是真的 CSV 文件,因此使用csv.reader 可能不合适。您希望示例输入文件的输出是什么?
  • 看不懂if row != int:这行???
  • 我最终想使用阅读器/解析器的输出作为我正在绘制的图形的坐标。因此,我认为,一个列表与 x 和 y 坐标在一起,就像它们现在在输出中的方式一样。我应该使用什么来代替 csv.reader?
  • Sylvain -- 我试图让它检查该行中是否有数字或字母,但我知道这不起作用......
  • 您想接受任何答案吗?你能解决你的问题吗?

标签: python list csv


【解决方案1】:

您的代码实际上对我很有效。我不知道你为什么会得到回溯。

tmp.csv

# 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

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

外壳输出

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

【讨论】:

    【解决方案2】:

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

    例如:

    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 对象,想想超级列表/字典,您可能可以直接从那里进行分析或操作。

    另外,如果您向我展示 cmets 在 csv 文件中的情况,我可以向您展示如何使用 read_csv 忽略它们。

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

    希望对你有帮助!

    【讨论】:

    • 谢谢!! CSV 文件看起来 完全 就像我问的问题一样。 cmets 遵循主题标签 (#)。 CSV 文件在坐标上没有标题。有什么办法可以按列号对它们进行排序吗?还是我需要标题?我真的无法更改 CSV 文件的格式。
    • 列号很好,但为列添加简单的名称可能是值得的,我会更新我的答案。
    • 另外,您可能希望将这两个 png 列表分成单独的文件。两者都不会正确导入数据框。如果您删除除数字之外的所有内容,那么上面的代码会很棒。
    • 另外,由于您是 python 新手,值得一提的是 IPython 以轻松交互地操作它,而无需编写代码编译运行重复。具体来说,请查看 IPython 笔记本。
    • 非常感谢您的帮助!
    猜你喜欢
    • 2011-08-12
    • 2010-10-28
    • 2016-04-06
    • 1970-01-01
    • 2021-11-04
    • 2019-03-09
    • 2021-09-02
    相关资源
    最近更新 更多