我正在尝试创建一个函数,它需要3个参数(List1,List2,“文件方向”)
该函数假定将两个列表按行串联在一起
List1 = [Paul, Jhon]
List2 = [Architect, Ingenieer]
直到列表为空。
Paul-建筑师
Jhon-工程师
我认为那里有问题
def appending(list1, list2, file):
filetoopen = open(file, "a")
for i in range(len(list1)): # posible error acá, figure it out then
filetoopen.write("\n" + list1[i] + " - " + list2[i] % (i+1))
filetoopen.close() # be sure you close the file before finish.
appending(names, work, "D:\papa.txt")
回溯(最近通话最近): 文件“ C:/Users/mauro/PycharmProjects/helloworld/writefiles.py”,第29行,在 附加(名称,作品,“ D:\ papa.txt”) 附加文件“ C:/Users/mauro/PycharmProjects/helloworld/writefiles.py”,第24行 filetoopen.write(“ \ n” + list1 [i] +“-” + list2 [i]%(i + 1)) TypeError:不是所有在格式化字符串期间转换的参数
答案 0 :(得分:0)
尝试一下:
list1 = ["Paul", "Jhon"]
list2 = ["Architect", "Ingenieer"]
def appending(list1, list2, file):
filetoopen = open(file, "w+")
for i in range(len(list1)): # posible error acá, figure it out then
filetoopen.write("\n {0} - {1}".format(list1[i], list2[i], (i+1)))
filetoopen.close() # be sure you close the file before finish.
appending(list1, list2, "a.txt")
a.txt中的输出
Paul - Architect
Jhon - Ingenieer
答案 1 :(得分:0)
出现此错误的原因仅仅是列表的成员不是字符串。一旦将它们用单引号或双引号引起来,就不会有错误。为了清楚起见,请看下面的代码-
def appending(list1, list2, file):
filetoopen = open(file, 'a')
for i in range(len(list1)):
filetoopen.write(str(list1[i]) + " - " + str(list2[i]) + "\n")
filetoopen.close()
List1 = ['Paul', 'Jhon']
List2 = ['Architect', 'Ingenieer']
filename = 'employee.txt'
appending(List1, List2, filename)
答案 2 :(得分:0)
L1 = ['Paul', 'Jhon']
L2 = ['Architect', 'Ingenieer']
filename="pytest.txt"
def list_concat(L1,L2,filename):
cL1=0
if len(L1) == len(L2):
with open(filename,'w') as writefile:
while cL1 < len(L1):
a = L1[cL1] + " " + L2[cL1] + '\n'
writefile.write(a)
cL1+=1
else:
pass
list_concat(L1,L2,filename)