【问题标题】:How can I turn csv file row column value into (row, column, value) in Python如何在 Python 中将 csv 文件行列值转换为(行、列、值)
【发布时间】:2016-07-28 08:56:57
【问题描述】:

for example, I read this 3x3 csv file.

       01   02   03

01 | 11 | 22 | 33 |

02 | 44 | 55 | 66 |

03 | 77 | 88 | 99 |

Then ,I want to output a new textfile like this photo.

→ (row, column, value)

→ (01, 01, 11)

→ (01, 02, 22)

→ (01, 03, 33)

→ (02, 01, 44)

我想通过数组或者for循环来使用python~~

像这样~

for x in range(len(row))

【问题讨论】:

  • 请不要使用图片来展示数据。而是以文本形式发布数据。您可以单击{ } 按钮将其格式化为代码。另外,请分享您的尝试(您阅读过文件吗?它是在列表中还是在其他数据结构中?您是否修改过该数据结构?)
  • 感谢您的建议。这是一个csv文件。我想把行列变成(行、列、值)final,输出一个文本文件

标签: python python-2.7 csv row


【解决方案1】:

假设你有这样的 example.csv 文件:

11|22|33
44|55|66
77|88|99

with open("example.csv") as handler:
    for r,l in enumerate(handler):
        for col, e in enumerate(l.split('|')):
            print('row: %s, col %s, value: %s' % (r+1, col+1, e))

【讨论】:

    【解决方案2】:
    with open("t.csv","rb") as open_file:#Read the file
          my_file = open_file.read().decode('utf-8','ignore')
    
        data = my_file.splitlines()
        data = [r.split('|') for r in data]
        row_len = len(data)
        for i,j in enumerate(data):
            col_len = len(data[0])
            start_index = 0
            while start_index<col_len:
                print (str(i).ljust(2,'0'),str(start_index).ljust(2,'0'),str(data[i][start_index]))
                start_index+=1
    

    【讨论】:

      猜你喜欢
      • 2021-08-12
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2018-03-29
      相关资源
      最近更新 更多