0

I am trying to read from csv file that only has one column. I need to combine all of the string into one for instance Row[1]=="Hallo." and Row[2]=="Goodbye." into string=="Hallo. Goodbye.".

import csv

data=None
with open('reviews.csv',encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        data2=(row[0])
        print(f'\n{data}.')
        line_count += 1
        data+=data2
    print(f'Processed {line_count} lines.')

Current error I'm getting is:

TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'

I have searched and read few posts but cannot seem to understand it.

7
  • 1
    You're being presented with a type error. Change data from None type to an empty string: data='' Commented Dec 24, 2019 at 20:56
  • @chb He would still need to check the type of the variable, so it would be more efficient to simply forgo concatenating it if it is of type NoneType, especially since concatenating an empty string won't actually do anything. Commented Dec 24, 2019 at 20:59
  • how many rows you have ?? Commented Dec 24, 2019 at 21:01
  • @GiovaniSalazar I have 10 rows Commented Dec 24, 2019 at 21:02
  • I wasn't paying attention @chb You were referring to him needing to initialize it - my bad Commented Dec 24, 2019 at 21:09

3 Answers 3

2

Because you are joining a bunch of strings, try using the join method of a string with a simple generator comprehension:

import csv

with open('reviews.csv',encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    data = "".join(row[0] for row in csv_reader if isinstance(row[0], str))

print(data)
print(f'Processed {csv_reader.line_num} lines')

Note that csv_reader internally keeps track of how many lines it has reviewed.

Sign up to request clarification or add additional context in comments.

Comments

1

Make a test file to work with.

with open("/tmp/junk.txt", 'w') as f: 
    for i in range(10): 
        f.write("Hello {}\n".format(i)) 

Now open your file.

with open("/tmp/junk.txt", 'r') as f: 
    data = f.readlines()

Clean up the whitespace (trailing new lines).

data = [i.strip() for i in data] 

And finally join it back together, space delimited.

print(" ".join(data))                                                                                                                                                          
Hello 0 Hello 1 Hello 2 Hello 3 Hello 4 Hello 5 Hello 6 Hello 7 Hello 8 Hello 9

Comments

0

A file with one column isn't a CSV. It is just a file with lines. To join up all the lines:

with open('reviews.csv') as f:
    print(' '.join(f.read().splitlines()))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.