繁体   English   中英

在python django中解析csv文件

[英]Parsing a csv file in python django

我正在尝试从已上传的csv文件读取数据。 首先,我要获取每一行,然后尝试通过用逗号分割数据来读取每一行中的数据,这对于理想情况是很好的,但是如果包含“,”(如地址字段),它将以错误的格式解析数据。

我想为val = v.split(',')提供一个更可靠的解决方案

我的代码是

 upload_file = request.FILES['upload_file']
    data = [row for row in csv.reader(upload_file.read().splitlines())]

    for v in data:
       # v is every row
       val = v.split(',') #spliting value of every row to get each record of every row 

如果您使用简单的read语句读取文件,例如:

data = upload_file.read()

# you can use the re library --> import re
rows = re.split('\n', data) # splits along new line
for index, row in enumerate(rows):
    cells = row.split(',')
    # do whatever you want with the cells in each row
    # this also keeps an index if you want the cell's row index

或者,您可以使用csv.reader模块:

file_reader = csv.reader(upload_file, delimiter=',')
for row in file_reader:
    # do something with row data.
    print(row)
    # would print the rows like
    # I, like, to, ride, my, bicycle
    # I, like, to, ride, my, bike

如果您希望拆分并访问每一行中的单词,那么re.split将是一个不错的选择:

re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']

来自的示例代码: https : //docs.python.org/2/library/re.html

CSV表示逗号分隔的值。 如果需要在CSV中编码字符串,则通常用引号将其引起来。 否则,您将无法正确解析文件:

$ cat sample.csv 
"131, v17",foo
bar,qux


>>> import csv
>>> with open('sample.csv', 'rb') as f:
...   r = csv.reader(f)
...   for row in r:
...     print row
... 
['131, v17', 'foo']
['bar', 'qux']

当然,如果您省略引号,则第一行将解析为3个字段。

您可以使用熊猫 这是一个基于此问题的示例:

>>> import sys, pandas
>>> if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO
## I assume your input is something like this:
>>> string = "a,b,c\n1,2,3\n4,5,6\n7,8,9\n"
>>> stringIO = StringIO(string)
>>> df = pandas.DataFrame.from_csv(stringIO, sep=',', index_col=False)
>>> print df
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

>>> print df.columns
Index([u'a', u'b', u'c'], dtype='object')

## access elements
>>> print df['a'][3]
7

DataFrame.from_csv的文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM