如何使用换行符@在python上读取csv [英] How to read csv on python with newline separator @
问题描述
我需要在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"
厚度:
换行符:@
到目前为止,我的代码:
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"'}]
推荐答案
根据 https://docs.python.org/2/library/csv.html :
读者被硬编码为将'\ r'或'\ n'识别为行尾,而忽略了行终止符.这种行为将来可能会改变." 因此,现在,提供参数lineterminator='@'
无效.
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')
根据python文档,现在您需要以一种可以将变量data
传递给csv.reader
(而不是文件stock.csv)的方式来调整算法:
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:
"" iterable参数可以是任何返回行的对象 每次迭代的输入,例如文件对象或列表. [...] "
"The "iterable" argument can be any object that returns a line of input for each iteration, such as a file object or a list. [...]"
因此,您可以将data.splitlines()
传递给csv.reader.
Hence you can pass data.splitlines()
to csv.reader.
这篇关于如何使用换行符@在python上读取csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!