Python 如何使用字符串和数字将值列表写入文本文件

Python 如何使用字符串和数字将值列表写入文本文件,python,python-3.x,Python,Python 3.x,我有三个清单: AList = ['name','name2'] BList = ['desg1','desg2'] InList = [1,2] 我正在使用以下代码片段将其写入文本文件: fo = open(filepath, "w") for i in zip(AList,BList,InList): lines=fo.writelines(','.join(i) + '\n') 但我得到了以下错误: TypeError: sequence item 2: expected s

我有三个清单:

AList = ['name','name2']
BList = ['desg1','desg2']
InList = [1,2]
我正在使用以下代码片段将其写入文本文件:

fo = open(filepath, "w")
for i in zip(AList,BList,InList):
     lines=fo.writelines(','.join(i) + '\n')
但我得到了以下错误:

TypeError: sequence item 2: expected string, int found

如何使用新行字符将值写入文本文件。

join
需要一系列
str
项作为第一个参数,但您的
InList
包含
int
值。只需将它们转换为
str

lines=fo.writelines(','.join(map(str, i)) + '\n')
我建议您在处理文件时将
块一起使用。您也可以将所有行写在一条语句中:

with open(filepath, "w") as fo:
    fo.writelines(','.join(map(str, x)) + '\n' for x in zip(AList,BList,InList))

join
需要字符串项,但在InList中有int。因此,在使用join之前,请将其转换为字符串,或者可以按如下方式执行:

AList = ['name','name2']
BList = ['desg1','desg2']
InList = ['1','2']

fo = open("a.txt", "w")
for i in range(len(AList)):
    dataToWrite = ",".join((AList[i], BList[i], str(InList[i]))) + '\n'
    lines=fo.writelines(dataToWrite)

文件中的预期输出是什么?@AshishRanjan name,desg1,1\n name,desg2,2