'Writing to a text file error - Must be str, not list
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
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()
Solution 1:[1]
write call in receipt.write(cells) expects a string, whereas you give it a list.
You can use join if you want everything to be concatenated (in this example, the values would be separated by dashes) :
receipt.write('-'.join(cells))
Hope it'll be helpful
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 3kt |
