python换行输入csv_如何使用换行符@在python上读取csv

I need to read a csv on Python, and the text file that I have has this structure:

"114555","CM13","0004","0","C/U"@"99172","CM13","0001","0","C/U"@"178672","CM13","0001","0","C/U"

delimeter: ,

newline: @

My code so far:

import csv

data = []

with open('stock.csv') as csvfile:

reader = csv.reader(csvfile, delimiter=',', lineterminator='@')

for row in reader:

data.append({'MATERIAL': row[0],'CENTRO': row[1], 'ALMACEN': row[2], 'STOCK_VALORIZADO' : row[3], 'STOCK_UMB':row[4]})

print(data) #this print just one row

This code only print one row, because it's not recognize @ as a newline,

and prints it with quotes:

[{'MATERIAL': '114555', 'CENTRO': 'CM13', 'ALMACEN': '0004', 'STOCK_VALORIZADO': '0', 'STOCK_UMB': 'C/U@"99172"'}]

解决方案

According to https://docs.python.org/2/library/csv.html :

"The reader is hard-coded to recognise either '\r' or '\n' as end-of-line, and ignores lineterminator. This behavior may change in the future." Hence for now, providing the argument lineterminator='@' will not work.

I think the best option is to read your entire file into a variable, and replace all '@' characters, you can do this as follows:

with open("stock.csv", "r") as myfile:

data = myfile.read().replace('@', '\n')

Now you need to adjust your algorithm in such a way that you can pass the variable data to csv.reader (instead of the file stock.csv), according to the python doc:

"The "iterable" argument can be any object that returns a line

of input for each iteration, such as a file object or a list. [...]"

Hence you can pass data.splitlines() to csv.reader.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值