0

I have a list of texts (reviews_train) which I gathered from a text file (train.txt).

reviews_train = []
for line in open('C:\\Users\\Dell\\Desktop\\New Beginnings\\movie_data\\train.txt', 'r', encoding="utf8"):
    reviews_train.append(line.strip())

Suppose reviews_train = ["Nice movie","Bad film",....]

I have another result.csv file which looks like

company     year
 a          2000
 b          2001
 .
 .
 .

What I want to do is add another column text to the existing file to look something like this.

company     year     text
 a          2000     Nice movie
 b          2001     Bad film
 .
 .
 .

The items of the list should get appended in the new column one after the other.

I am really new to python. Can some one please tell me how to do it? Any help is really aprreciated.

EDIT: My question is not just about adding another column in the .csv file. The column should have the texts in the list appended row wise.

EDIT: I used the solution given by @J_H but I get this error enter image description here

rini saha
  • 195
  • 1
  • 1
  • 11
  • Possible duplicate of [How to add a new column to a CSV file?](https://stackoverflow.com/questions/11070527/how-to-add-a-new-column-to-a-csv-file) – R4444 May 04 '19 at 21:55
  • @Ruturaj I edited my question for better understanding – rini saha May 05 '19 at 07:45

1 Answers1

0

Use zip():

def get_rows(infile='result.csv'):
    with open(infile) as fin:
        sheet = csv.reader(fin)
        for row in sheet:
            yield list(row)


def get_lines(infile=r'C:\Users\Dell\Desktop\New Beginnings\movie_data\train.txt'):
    return open(infile).readlines()


for row, line in zip(get_rows(), get_lines()):
    row.append(line)
    print(row)

With those 3-element rows in hand, you could e.g. writerow().

EDIT

The open() in your question mentions 'r' and encoding='utf8', which I suppressed since open() should default to using those.

Apparently you're not using the python3 mentioned in your tag, or perhaps an ancient version. PEPs 529 & 540 suggest that since 3.6 windows will default to UTF-8, just like most platforms. If your host manages to default to something crazy like CP1252, then you will certainly want to override that:

    return open(infile, encoding='utf8').readlines()
J_H
  • 17,926
  • 4
  • 24
  • 44