Writing to a text file error - Must be str, not list

Jordan picture Jordan · May 31, 2016 · Viewed 17.2k times · Source

I have been having problems with some code I am writing. Basically, when I run the code I enter an 8 digit number and it should scan the CSV file to see if the number is inside the file. If it is, the row should be written to the text file. However, when I run it and I enter a number, I get this:

TypeError: must be str, not list

(EDIT) And even when it is fixed, the output is:

<_io.TextIOWrapper name='receipt.txt' mode='a' encoding='cp1252'> 

My code is as follows:

import csv
import sys
import re

addItem = ""
gtinNum = ""
quantity = 0
totalPrice = 0

receipt = open("receipt.txt", "r+")
f = open("ChocolateCSV.csv", "rt")

def scanGTIN():
    rows = re.split('\n', f.read())

    for index, row in enumerate(rows):
        global cells
        cells = row.split(',')
        if gtinNum in cells:
            receipt.write(cells)

def gtinQuestion():
    global gtinNum
    gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")

    if gtinNum.isdigit() == False or len(gtinNum) != 8:
        gtinQuestion()
    elif gtinNum.isdigit() == True and len(gtinNum) == 8:
        scanGTIN()


gtinQuestion()

Any help is appreciated, thanks.

Answer

nekomatic picture nekomatic · May 31, 2016

The write method of a Python text file takes a string (str), not a list.

If you want to duplicate matching rows from the input file to the output, as your description implies, I think you want to either replace your

receipt.write(cells)

with

receipt.write(",".join(cells))

or replace:

rows = re.split('\n', f.read())

with

rows = f.readlines()

and

receipt.write(cells)

with

receipt.write(row)

The first example joins the elements of cells back into a string, inserting a comma between each one. The second one means that rows is a list containing all the rows of the input file, rather than an iterator that reads one row at a time. The first method is probably better as it avoids reading a large file into memory, just as long as you realise what it means to get an iterator rather than a list.