Using csv module to read ascii delimited text?

前端 未结 4 2049
故里飘歌
故里飘歌 2020-12-21 07:16

You may or may not be aware of ASCII delimited text, which has the nice advantage of using non-keyboard characters for separating fields and lines.

Writing this out

4条回答
  •  忘掉有多难
    2020-12-21 08:09

    Hey I was struggling with a similar problem all day. I wrote a function heavily inspired by @martineau that should solve it for you. My function is slower but can parse files delimited by any kind of string. Hope it helps!

    import csv
    
    def custom_CSV_reader(csv_file,row_delimiter,col_delimiter):
    
        with open(csv_file, 'rb') as f:
    
            row = [];
            result = [];
            temp_row = ''
            temp_col = ''
            line = ''
            go = 1;
    
            while go == 1:
                while go == 1:
                    ch = f.read(1)
    
                    if ch == '':  # end of file?
                        go = 0
    
                    if ch != '\n' and ch != '\t' and ch != ',':
                        temp_row = temp_row + ch
                        temp_col = temp_col + ch
                        line = line + ch
    
                    if row_delimiter in temp_row:
                        line = line[:-len(row_delimiter)]
    
                        row.append(line)
    
                        temp_row = ''
                        line= ''
    
                        break
    
                    elif col_delimiter in temp_col:
                        line = line[:-len(col_delimiter)]
                        row.append(line)
                        result.append(row)
    
                        row = [];
                        temp_col = ''
                        line = ''
                        break
        return result
    

提交回复
热议问题