编写一个程序,要求用户提供一个文件,其中包含要完成的项目列表和输出文件的名称。然后,您的程序应该将列表编号,并将项目编号写入输出文件。例如,如果输入文件是:
Finish my python homework.
Buy milk.
Do laundry.
Update webpage.
然后输出文件将是:
1. Finish my python homework.
2. Buy milk.
3. Do laundry.
4. Update webpage.
我尝试按以下方式执行此操作:
infileNames=input("what is the file that contain a list of items?")
outfileName=input("what is the file that contain a list of items?")
infile=open(infileName,"r")
outfile=open(outfileName,"w")
data=infile.read()
countnolines=len(open(infileName).readlines())
for p in range(1,countnolines+1):
print(p,data,file=outfile)
infile.close()
outfile.close()
但是我的outfile看起来像:
1 Finish my python homework.
Buy milk.
Do laundry.
Update webpage.
2 Finish my python homework.
Buy milk.
Do laundry.
Update webpage.
3 Finish my python homework.
Buy milk.
Do laundry.
Update webpage.
4 Finish my python homework.
Buy milk.
Do laundry.
Update webpags
* 强文 *感谢大家的帮助
答案 0 :(得分:5)
infilenames = input("what is the file that contain a list of items?")
outfileName = input("what is the file that contain a list of items?")
infile = open(infilenames)
outfile = open(outfilename,'w')
data = infile.readlines() # a list of the lines of infile
lineno = 1
for line in data:
print(lineno,line.strip(),file=outfile)
lineno += 1
outfile.close()
infile.close()
with open(INPUT_FILE) as in_, open(OUTPUT_FILE, "w") as out:
for i, line in enumerate(in_, 1):
out.write("{}. {}\n".format(i,line.strip()))