如何在一个文件的单行上输出3个项目?

2024-03-29 15:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个程序,允许用户不断输入三个项目集,每个输入提示一个,然后将三个值输出到文本文件中的一行。你知道吗

下面是一些基本的例子

text_file = open("filename", "w")

While True:
      Code = input("Enter code")
      Description = input("Enter description")
      Price = input("Enter price")

有人能帮我吗?你知道吗

编辑: 到目前为止,我就在这里。你知道吗

text_file = open("file.txt", "w")

while True:
      user_input = input("Enter a code, description and price")
      split = user_input.split(" ")
      split = str(split)
      text_file.write(split)

唯一的问题是它不允许我输出列表。你知道吗


Tags: 项目text用户程序trueinputcodedescription
3条回答

如果使用Python>;=3.6并且不需要与旧版本兼容:

text_file.write(f'{Code} {Description} {Price}\n')

否则(改编自另一个答案):

text_file.write('{} {} {}\n'.format(Code, Description, Price))

请注意,事实上,标准惯例是变量名应以小写字母开头。所以应该使用codedescriptionprice作为变量名。你知道吗

sep = ','   # separator character
textfile.write(sep.join([Code, Description, Price]) + '\n')
with open("filename.txt", "w") as f:
    while True: 
         f.write(input("Enter code : ")+' ')
         f.write(input("Enter description : ")+' ')
         f.write(input("Enter price : ")+'\n')

相关问题 更多 >