我想创建一个程序,允许用户继续输入三个项目的集合,每个输入提示一个,然后将三个值输出到文本文件中的一行。
这是一些基本的例子
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)
唯一的问题是它不允许我输出列表。
答案 0 :(得分:3)
sep = ',' # separator character
textfile.write(sep.join([Code, Description, Price]) + '\n')
答案 1 :(得分:3)
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')
答案 2 :(得分:3)
如果使用Python> = 3.6并且不需要与旧版本兼容:
data Month1;
input Name $ sales;
cards;
Joyce 235
Marsha 352
Bill 491
Vernon 210
Sally 418
;
data Month2;
input Name $ sales;
cards;
Joyce 169
Marsha 281
Bill 315
Vernon 397
Sally 305
;
data Month3;
input Name $ sales;
cards;
Joyce 471
Marsha 314
Bill 394
Vernon 291
Sally 337
;
data Month4;
input Name $ sales;
cards;
Joyce 338
Marsha 259
Bill 310
Vernon 432
Sally 362
;
data Month5;
input Name $ sales;
cards;
Joyce 209
Marsha 355
Bill 302
Vernon 416
Sally 475
;
data Month6;
input Name $ sales;
cards;
Joyce 306
Marsha 472
Bill 351
Vernon 405
Sally 358
;
options sgen;
%let qtr=qtr1;
%Macro ProcSql;
Proc Sql;
%if &qtr=qtr1 %then %do;
%let month1=month1;
%let month2=month2;
%let month3=month3;
%end;
%else %if &qtr=qtr2 %then %do;
%let month1=month4;
%let month2=month5;
%let month3=month6;
%end;
%else %if &qtr=qtr3 %then %do;
%let month1=month7;
%let month2=month8;
%let month3=month9;
%end;
%else %%if &qtr=qtr4 %then %do;
%let month1=month10;
%let month2=month11;
%let month3=month12;
%end;
create table &qtr as
select &month1.name, &month1.sales as m1sales, &month2.sales as m2sales,
&month3.sales as m3sales, sum(m1sales, m2sales, m3sales) as
qtrsales
from &month1, &month2, &month3
where &month1.name=&month2.name=&month3.name;
select sum(m1sales) as m1total, sum(m2sales) as m2total, sum(m3sales) as
m3total,
sum(qtrsales) as qtrtotal
from &qtr;
%mend ProcSql;
%ProcSql;
否则(改编自另一个答案):
text_file.write(f'{Code} {Description} {Price}\n')
请注意,变量名称应以小写字母开头,这是事实上的标准约定。因此,您应该使用text_file.write('{} {} {}\n'.format(Code, Description, Price))
,code
和description
作为变量名称。
答案 3 :(得分:0)
假设用户使用空格分割三个字段(即1232示例产品$ 24.95),您知道第一个空格将代码与描述分开,最后一个空格将描述与价格分开。然后:
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))