Writing to a text file error - Must be str, not list
Solution 1
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.
Solution 2
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
Jordan
Updated on July 19, 2022Comments
-
Jordan almost 2 years
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.