How to read csv in python with @ line separator
I need to read a csv in Python and the text file I have has the following structure:
"114555","CM13","0004","0","C/U"@"99172","CM13","0001","0","C/U"@"178672","CM13","0001","0","C/U"
delimeter :,
newline: @
My code:
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 prints one line, because it does 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 hardcoded to recognize" \ r "or" \ n "as the end of the line and ignore the lineterminator. This behavior may change in the future." Hence, providing an argument lineterminator='@'
will not work at this point .
I think the best option is to read your whole file into a variable and replace all the "@" characters, you can do it like this:
with open("stock.csv", "r") as myfile:
data = myfile.read().replace('@', '\n')
Now you need to set up your algorithm to pass the variable data
in csv.reader
(instead of the stock.csv file), according to the python doc:
The "iterable" argument can be any object that returns an input string for each iteration, such as a file object or a list. [...] "
Hence, you can pass data.splitlines()
to csv.reader.