【问题标题】:extracting row from CSV file with Python / Django使用 Python / Django 从 CSV 文件中提取行
【发布时间】:2022-09-23 00:07:50
【问题描述】:

嘿,我正在尝试从 CSV 文件中提取某些行,其中包含以下形式的内容:

POS,Transaction id,Product,Quantity,Customer,Date
1,E100,TV,1,Test Customer,2022-09-19
2,E100,Laptop,3,Test Customer,2022-09-20
3,E200,TV,1,Test Customer,2022-09-21
4,E300,Smartphone,2,Test Customer,2022-09-22
5,E300,Laptop,5,New Customer,2022-09-23
6,E300,TV,1,New Customer,2022-09-23
7,E400,TV,2,ABC,2022-09-24
8,E500,Smartwatch,4,ABC,2022-09-25

我写的代码如下

def csv_upload_view(request):
    print(\'file is being uploaded\')

    if request.method == \'POST\':
        csv_file = request.FILES.get(\'file\')
        obj = CSV.objects.create(file_name=csv_file)

        with open(obj.file_name.path, \'r\') as f:
            reader = csv.reader(f)
            reader.__next__()
            for  row in reader:
                data = \"\".join(row)
                data = data.split(\";\")
                #data.pop()
                print(data[0], type(data))
                transaction_id = data[0]
                product = data[1]
                quantity = int(data[2])
                customer = data[3]
                date = parse_date(data[4])

在控制台中,我得到以下输出:

Quit the server with CONTROL-C.
[22/Sep/2022 15:16:28] \"GET /reports/from-file/ HTTP/1.1\" 200 11719
file is being uploaded
1E100TV1Test Customer2022-09-19 <class \'list\'>

这样我才能得到正确的行,将所有内容连接起来。相反,如果我在\" \".join.row我用空格分隔整行 - 我想做的是访问这一行

transaction_id = data[0]
                product = data[1]
                quantity = int(data[2])
                customer = data[3]
                date = parse_date(data[4])

但我总是得到一个

IndexError: list index out of range

我也尝试使用 data.replace(\" \",\";\") 但这给了我另一个错误,并且数据类型变成了字符串而不是列表:

ValueError: invalid literal for int() with base 10: \'E\'

有人可以告诉我我在这里缺少什么吗?

    标签: python


    【解决方案1】:

    我不确定您为什么要加入/拆分行。你意识到你的分割是使用分号吗?

    我会期待这样的事情:

    result = []
    with open(f_name, 'r') as src:
        src.readline()  # burn the header row
        reader = csv.reader(src)   # if you want to use csv reader
        for line in reader:
            data = line.strip().split(',')   # strip any trailing whitespace and split it into elements by comma
            ...   either put it into result for list-of-lists or parse it out..
    

    就您的问题而言...您提到提取“特定行”,但您没有说明如何找到这样的行。如果您知道行索引/编号,您可以使用readline 或类似的方式烧掉行数,或者在阅读时保留一个计数器。如果您在数据中查找关键字,只需在拆分行之前或之后弹出一个条件语句。

    【讨论】:

      【解决方案2】:

      这样您就可以拆分行(并根据一些提供的值找到您想要的行)

      with open('data.csv') as csv_file:
          csv_reader = csv.reader(csv_file, delimiter = ',')
      
          line_count = 0
      
          for row in csv_reader:
              # Line 0 is the header
      
              if line_count == 0:
                  print(f'Column names are {", ".join(row)}')
                  line_count += 1
              
              else:
                  line_count += 1
                  # Here you can check if the row value is equal what you're finding
                  # row[0] = POS
                  # row[1] = Transaction id
                  # row[2] = Product
                  # row[3] = Quantity
                  # row[4] = Customer
                  # row[5] = Date
      
                  if row[2] = "TV": 
                      transaction_id = row[0]
                      product = row[1]
                      quantity = row[2]
                      customer = row[3]
                      date = row[4]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-22
        • 2022-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 2021-09-22
        相关资源
        最近更新 更多