【问题标题】:Parsing a csv file in python django在 python django 中解析 csv 文件
【发布时间】:2015-04-07 09:30:21
【问题描述】:

我正在尝试从已上传的 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 

【问题讨论】:

  • 查看csv module
  • csv.reader已经进行逗号分割等等——为什么你会在 `v.split 中找到任何附加值?!

标签: python django csv


【解决方案1】:

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

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

【讨论】:

  • 使用来自 csv 模块的流消费者的好处。减少数据操作和内存占用。但不应该只是 csv.reader(upload_file, delimiter=',') 吗?
  • @spectras 啊,很好。我写的太快了。我会编辑。
【解决方案2】:

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

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

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

【讨论】:

  • 没有回答这个问题,因为他指出他必须支持包含逗号的字段。这意味着能够支持引号括起来的字段。
【解决方案3】:

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 个字段。

【讨论】:

    【解决方案4】:

    您可以使用pandas。下面是一个基于this question的例子:

    >>> 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
    

    Documentation for DataFrame.from_csv

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-26
      • 2018-03-08
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多