poisonishere
poisonishere

Reputation: 43

How do you output 3 items on a single line in a file?

I want to make a program that allows a user to keep entering sets of three items, one for each input prompt, and then output the three values to a single line in a text file.

Here is some basic example

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

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

Can anyone help me?

EDIT: So this is where I am so far.

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)

The only problem is it doesn't let me output a list.

Upvotes: 1

Views: 103

Answers (4)

PRMoureu
PRMoureu

Reputation: 13327

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')

Upvotes: 3

Penguin Brian
Penguin Brian

Reputation: 2131

If using Python >= 3.6 and compatibility with older versions is not required:

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

Otherwise (adapted from another answer):

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

Note that it is the defacto standard convention that names of variables should start with a lowercase letter. So you should use code, description, and price for the variable names.

Upvotes: 3

Prune
Prune

Reputation: 77847

sep = ','   # separator character
textfile.write(sep.join([Code, Description, Price]) + '\n')

Upvotes: 3

TheoretiCAL
TheoretiCAL

Reputation: 20571

Assuming the users splits the three fields with a space (i.e 1232 Example Product $24.95) you know that the first space separates the code from description, and the last space separates the description from price. Then:

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

while True:
      user_input = input("Enter Code Description Price:")
      split_input = user_input.split(' ')
      code = split_input[0]
      description = ' '.join(split_input[1:-1])
      price = split_input[-1]

text_file.write('{} {} {}\n'.format(code, description, price))

Upvotes: 0

Related Questions