写入文本文件错误 - 必须是 str,而不是列表

Jor*_*dan 6 python csv text writing

我在编写一些代码时遇到了问题。基本上,当我运行代码时,我输入了一个 8 位数字,它应该扫描 CSV 文件以查看该数字是否在文件中。如果是,则应将该行写入文本文件。但是,当我运行它并输入一个数字时,我得到了这个:

TypeError: must be str, not list
Run Code Online (Sandbox Code Playgroud)

(编辑)即使是固定的,输出也是:

<_io.TextIOWrapper name='receipt.txt' mode='a' encoding='cp1252'> 
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

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()
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏,谢谢。

nek*_*tic 2

Python 文本文件的方法write采用字符串 ( str),而不是列表。

如果您想将输入文件中的匹配行复制到输出,正如您的描述所暗示的那样,我认为您想要替换您的

receipt.write(cells)
Run Code Online (Sandbox Code Playgroud)

和

receipt.write(",".join(cells))
Run Code Online (Sandbox Code Playgroud)

或替换:

rows = re.split('\n', f.read())
Run Code Online (Sandbox Code Playgroud)

和

rows = f.readlines()
Run Code Online (Sandbox Code Playgroud)

和

receipt.write(cells)
Run Code Online (Sandbox Code Playgroud)

和

receipt.write(row)
Run Code Online (Sandbox Code Playgroud)

第一个示例将 back 的元素连接cells到一个字符串中,并在每个元素之间插入逗号。第二个意味着这rows是一个包含输入文件所有行的列表,而不是一次读取一行的迭代器。第一种方法可能更好,因为它避免将大文件读入内存,只要您意识到获取迭代器而不是列表意味着什么即可。