Reputation: 27
Write a program that asks the user for a file containing a list of items to be completed and a name for an output file. Your program should then write the list, with item numbers to the output file. For example, if the input file is:
Finish my python homework.
Buy milk.
Do laundry.
Update webpage.
Then the output file would be:
1. Finish my python homework.
2. Buy milk.
3. Do laundry.
4. Update webpage.
I tried to do this the following way:
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()
But my outfile looks like:
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
*strong text*thanks guys for help
Upvotes: 0
Views: 119
Reputation: 54243
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()))
Upvotes: 5