CSV reader is generating additional empty entries

I am working with an input csv file that has a varying number of columns which I am trying to convert into a list. The issue I am facing is that my test is parsing the csv file and creating a list with additional elements around the csv columns. Ideally, I would like the list to only contain the csv elements, but right now it also includes empty quoted elements. I need some assistance in figuring out what options I might be missing when using the csv reader.

Here is an example of the output:

$ python cond.py
opening conditions file  conditions.lst
parser  0  input line:
"string1:", "string1b,string1c,"
output list elements:
['string1:']
['', '']
['']
['string1b,string1c,']
[]

parser  1  input line:
"stringa:", "stringb,stringc,"
output list elements:
['stringa:']
['', '']
['']
['stringb,stringc,']
[]

parser  2  input line:
"string3:", "string3next=abc", "string3b","string3c:", "string3d"
output list elements:
['string3:']
['', '']
['']
['string3next=abc']
['', '']
['']
['string3b']
['', '']
['string3c:']
['', '']
['']
['string3d']
[]

Input file:

$ cat conditions.lst
"string1:", "string1b,string1c,"
"stringa:", "stringb,stringc,"
"string3:", "string3next=abc", "string3b","string3c:", "string3d"

Python cond.py file:

$ cat cond.py

from __future__ import print_function
#from csv import reader

import re
import sys
import csv

# variables

conditionsFile = "conditions.lst"
parserConditions = []
numOfParsers = 0


print("opening conditions file ", conditionsFile)
with open(conditionsFile, "r") as cf:
  for line in cf:
    print("parser ", numOfParsers, " input line:")
    print(line.strip())

    r = csv.reader(line, quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True)
    print("output list elements:")
    for cline in  r:
      print(cline)

    numOfParsers = numOfParsers + 1
    print("")

  print("total number of parsers: ", numOfParsers)

Update: With the help of @Jean-FrançoisFabre, I haven't identified the root cause yet, but I have come up with a workaround - placing the csv elements into a list and then removing any blank elements.

for cline in  r:
  conditions.extend(cline)

conditions = filter(None, conditions)
print(conditions)

Answer â„–1

csv.reader function requires a file-like object, not a string. This causes it to iterate strangely over the characters of a line instead of the lines of a file. To resolve this, you can use:

from __future__ import print_function
import csv

with open('conditions.lst','rb') as cf:
    r = csv.reader(cf,skipinitialspace=True)
    for line in r:
        print(line)

Here is the expected output:

['string1:', 'string1b,string1c,']
['stringa:', 'stringb,stringc,']
['string3:', 'string3next=abc', 'string3b', 'string3c:', 'string3d']

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating infinite scroll pages with scrapy and selenium: a comprehensive guide

Struggling with using scrapy +selenium to extract data from a webpage that loads content dynamically as we scroll down? Take a look at the code snippet below where I encounter an issue with getting the page source and end up stuck in a loop. import scrap ...

Accessing new data added with ForeignKey in Django Admin Area

Let's consider a scenario where we have the following models: # models.py from django.db import models class Category(models.Model): title = models.CharField(max_length=60) class CategoryDescription(models.Model) category = models.Foreign ...

LibGDX's latest project featuring a vibrant yellow warning triangle

Recently, I embarked on a new endeavor with LibGDX. While normally I overlook the presence of yellow warning triangles in my projects, this time it has become somewhat bothersome. Is there a way to address this issue? Here is a visual representation: ...

Persistence of Flask-SQLAlchemy changes does not apply

Building a web application where user actions can impact bar graphs, some changes are not saved. Reloading the page sometimes shows the updated bar graphs, indicating that the user's actions were saved. However, upon further reloads, the changes may o ...

Retrieving URLs for CrawlSpider using Scrapy

I have developed a script to systematically catalog all URLs on a website. Currently, I am utilizing CrawlSpider with a rules handler to manage the scraped URLs. The "filter_links" function checks an existing table for each URL and writes a new entry if i ...

Setting the Host Parameter during the creation of a user in a Rackspace Cloud Database Instance

Rackspace has recently implemented a new feature that allows users to select specific cloud servers as hosts when creating a user in a cloud database instance. This ensures that the specified user can only be accessed from those designated cloud servers. ...

Transform Python code into Scala

After transitioning from Python to Scala, I found myself struggling with the conversion of a program. Specifically, I encountered difficulties with two lines of code pertaining to creating an SQL dataframe. The original Python code: fields = [StructField ...

Decreasing window size near boundary for smoothing functions with fixed endpoints

I'm in search of a solution that can perform simple boxcar smoothing with the added requirement of accepting a boundary condition. Specifically, I need a function, either pulled from an existing library or written in Python for performance, that can h ...

Error encountered while attempting to install PyAudio using conda due to inability to satisfy certain requirements

Whenever I try to run conda install PyAudio, I encounter this error message in my terminal. Just so you know, I am using Python version 3.10.7. PS C:\Users\Admin\PycharmProjects\pythonProject2> conda --version conda 4.12.0 PS C:&bsol ...

Mastering the art of efficiently capturing syntax errors using coroutines in Python

Currently, I am in the process of developing a Python script that runs two tasks simultaneously. Transitioning from JavaScript to Python's async/await coroutine features has presented some challenges for me as I have encountered unexpected behavior. ...

What is the best way to delete any blank strings from a list that is associated with a particular key within a group of dictionaries?

As a newcomer to Python with a background in social sciences, I am making an effort to articulate my issue and sincerely appreciate any assistance! My challenge involves a list of dictionaries containing data on online recipes. Within the specific key [&a ...

"Encountered an issue with locating elements using the driver.find_element

I need assistance in automating the process of clicking on the "Create New Network" button using Selenium. <button type="button" id="dt-refreshBtn" class="btn wc-btn--link" data-label="Create New Network" role=&q ...

Struggling to smoothly slide a button to the right with Python Selenium WebDriver

I've created a script to automate website registration using Selenium with Python, but I'm struggling to find the code that would enable me to slide the slider to the right in order to complete the registration process. Here is the link to the we ...

An error of 'Address already being used' encountered while utilizing cookiecutter-flask

My operating system is OS X 10.14.3 and I am attempting to utilize the impressive cookiecutter-flask project. I have diligently followed the instructions provided in the README.rst: cookiecutter https://github.com/sloria/cookiecutter-flask.git # My test p ...

Incorporating a data point into a specific column within an array

As a physics undergraduate student with limited computer programming experience, particularly in Python, I am currently working on a script to shift the coordinate system of a set of coordinates from a .xyz file. The goal is to center the coordinate system ...

Ending a Python Script from a PHP File: Best Practices

In the final stages of my IoT-based project, I am currently developing a website in php that interacts with sensors controlled by a raspberry pi board using a python script. One feature I am trying to implement is allowing users to turn these sensors on an ...

Click on a previously saved Selenium element once the page has been reloaded

Is there a way to achieve a similar functionality where each "button" press triggers a page reload? element = driver.find_element_by_xpath("//select[@name='name']") all_options = element.find_elements_by_tag_name("option") for option in all_opti ...

Verify if the file uploaded in django is a zip file

I'm working on a POST method handler in Django that deals with uploaded files, and I want to ensure that the file is a valid zip file before continuing. My current code snippet looks like this: @login_required(login_url="login/") def upload(request) ...

Python code for generating a festive holiday tree

Looking for a way to represent a Christmas tree using just a sentence. Here's the code I've come up with so far, but it's not quite right. sentence = 'The whole Christmas tree.' for word in sentence.split(): for i, char in enu ...

Exploring mammoth text data in Python

I am currently diving into Python development with my first project, which involves parsing a hefty 2GB file. After discovering that processing it line by line would be agonizingly slow, I decided to opt for the buffering method. Here's what I'm ...