在Python中单独列出输入值

时间:2017-01-07 20:30:18

标签: python split

我正在使用Python 3.4,我在下面编写了Python代码。我想要的是在用户输入时将用户的姓名和年龄保存到文本文件中。我希望看到输入以逗号分隔的行。

我试过了.split(),但它没有用。我很乐意提供任何帮助,谢谢。

ages = [] 
name = ' ' 
age = ' ' 
fileName = 'demo.txt' 
#you can do it csv 
WRITE = 'w'
APPEND = 'a' 
while name != 'done':
   name = input('what is your name: ')
   age = input('what is your age: ')
   guests.append(name)
   ages.append(age)

guests.remove('done')
ages.remove('done')
file = open(fileName, mode = WRITE)
file.writelines(guests)
file.writelines(ages)
file.close()

1 个答案:

答案 0 :(得分:0)

这会写一个包含访客和年龄的文件

{
  "cmd": [
    "bash",
    "--login",
    "-c",
    "source /home/ubuntu/.virtualenvs/foo/bin/activate && python whatever.py"
  ],
  # ... rest of the configuration
}

demo.txt

with  open(fileName, mode = WRITE) as inpt:
    for i in range(len(guests)):
        inpt.write(guests[i] + ", " + ages[i] + "\n")

或者这样:

Andi, 12
Bertha, 34
Claus, 99

demo.txt

with  open(fileName, mode = WRITE) as inpt:
    inpt.write(",".join(guests))
    inpt.write("\n")
    inpt.write(",".join(ages))