CSV读取器拆分错误的分隔符Python 3.x.x

时间:2017-09-18 21:09:50

标签: python python-3.x csv

这可能可能 肯定是我的错,但我的逗号分隔值读取器似乎是在错误的分隔符上拆分。我正在尝试将像“3:00”这样的单独时间值放到像["3", "00"]这样的列表中,然后将这些数字与另一个相同格式的列表进行比较。

CSV阅读器:

    rows = []  
    self.file_name = None  
    if file == "pressure":  
        self.file_name = self.pressure_group 
    if file == "surface":  
        self.file_name = self.surface_interval  
    if file == "repetive": 
        self.file_name = self.rnt_calculator

    with open(self.file_name) as fp:  
        csvreader = csv.reader(fp)  

        for row in csvreader:  
            rows.append(row)  

    index = 0  
    for l in rows[0]:
        index += 1
        if file == "pressure":
            self.pressure_reference[index] = l

        if file == "surface":
            self.surface_reference[index] = l

        if file == "repetive":
            self.repetive_reference[index] = l

    del rows[0]
    if file == "pressure":
        self.pressure_rows = rows

    if file == "surface":
        self.surface_rows = rows

    if file == "repetive":
        self.repetive_rows = rows

然后我使用self.surface_rows

             for row in self.surface_rows:
                print(str(time_to_find) + pressure_group)
                if row[0] == pressure_group:
                    for item in row[1]:
                        time_found = item.split(":")
                        if time_found[0] == time_to_find[0]:
                            if time_found[1] >= time_to_find[1]:
                                cprint(str(time_found) + " TIME FOUND", "red", attrs=["bold"])
                        if time_found[0] >= time_to_find[0]:
                            cprint(str(time_found) + " TIME FOUND", "cyan", attrs=["bold"])

time_to_find取自s,s取s = input(),然后拆分s.split(":")

我得到的与我想要的一样

显然我的time_found是“0”而不是“1:30”或“1:25”因此它不能再被拆分而且没有什么真正改变,除了它现在是一个项目列表({{ 1}})。现在我想要["0"]之类的time_found成为"1:30"

我的CSV文件

csv文件存储在.txt文件中,可以找到here

["1", "30"]

1 个答案:

答案 0 :(得分:1)

这是一个如何分割它的工作示例。 基本上,您必须在比较之前将字符串转换为整数。

import tempfile
import csv

input_name = None
with tempfile.NamedTemporaryFile(delete=False) as f:
    input_name = f.name
    f.write("""BLANK,Z,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A
Z,0:00,0:52,1:44,2:37,3:29,4:21,5:13,6:06,6:58,7:50,8:42,9:34,10:27,11:15,12:53,13:30
O,0:00,0:00,0:52,1:44,2:37,3:29,4:21,5:13,6:06,6:58,7:50,8:42,9:34,10:27,11:15,12:53
N,0:00,0:00,0:00,0:52,1:44,2:37,3:29,4:21,5:13,6:06,6:58,7:50,8:42,9:34,10:27,11:15
M,0:00,0:00,0:00,0:00,0:52,1:44,2:37,3:29,4:21,5:13,6:06,6:58,7:50,8:42,9:34,10:27""")

rows = []
with open(input_name, 'r') as fp:
    csvreader = csv.reader(fp)

    for row in csvreader:
        rows.append(row)

    # ingore first row and first column, split the rest
    for row in rows[1:]:
        for col in row[1:]:
            hours, mins =  col.split(':')
            print(int(hours), int(mins))

这导致:

(0, 0)
(0, 52)
(1, 44)
(2, 37)
(3, 29)
(4, 21)
(5, 13)
(6, 6)
(6, 58)
(7, 50)
(8, 42)
(9, 34)
(10, 27)
...