我有持有2动物信息 [('alyson', '5', 'dog'), ('merlin', '6', 'cat')]
我需要在列表重新排列动物品种,姓名,年龄的顺序,然后去除特殊字符,并将它们写回到列表一个.txt文件。 我试过.remove
作为一个列表。我的下一个试验和错误是将列表转换为字符串,并尝试使用.replace
方法。没有任何方法奏效。我可能错误地使用了它们。任何意见,我在哪里可以看看,非常感谢重排列表,并删除特殊字符
编辑:该程序是假设拉动动物信息的格式是:品种,名称,年龄。在我的一个功能中,我需要重新排列它并输出它的名字,年龄,品种。然后用户会提示动物是否被采纳或是否有新的动物进入,我的宠物列表会反映这一点。一旦用户完成,程序将把更新后的列表保存回原来的格式。我遇到了特殊字符的问题。我做pet_list [0],它会给我(“阿利森”的输出的打印测试,
#This function opens the file and arranges it into an output order
#format of the file would be: dog, alyson, 5
def get_pet(file):
f = open(file)
pet_info = f.readlines()
pet = []
for line in pet_info:
info = line.split()
pet_type = info[0]
name = info[1]
age = info[2]
pet.append((name, age, pet_type))
return pet
#this is the function where i was planning on rearranging the list back to how it originally was and
#rewrite them back onto a text file
def do_save(pet_list, current_file, transfer, adopt_list, transfer_list):
shelter_list = open(current_file, 'w')
print(pet_list)
print(type(pet_list))
for line in pet_list:
print(type(line))
shelter_list.write(str(line))
shelter_list.close()
adopt = open("adopted.txt", 'w')
adopt.write(str(adopt_list))
adopt.close()
transfer_file = open(str(transfer), 'w')
transfer_file.write(str(transfer_list))
transfer_file.close()
如果您希望人们提供帮助,您需要包括样本输入,期望的输出以及“什么都不工作”的描述。 –
对不起,如果我没有更清楚。虐待编辑它以反映, –
这是你想要的:'shelter_list.write(“”.join(line)+“\ n”)' – Barmar