Write lines in loop problem

This is the place for queries that don't fit in any of the other categories.

Write lines in loop problem

Postby varikasutaja » Tue Mar 25, 2014 4:21 pm

Hi !

I have problem in Reading/Writing files part.
For example if i use these codes , everything works fine :

Code: Select all
a = input("enter something")
f = open("info.txt", "w")
f.write(a+ "\n")
f.close()


OR

Code: Select all
f = open('info.txt')
a= f.readline()
print(a)
f.close()


When i try to use read/write inside while loop ,then i cant make these things work :(


My EXAMPLE:

Code: Select all
from random import randint

f = open("info.txt", "w")
a=int(input("enter products count"))
i=0
while i<a:
     bb=int(randint(30, 150))
     i+=1
     print(bb)
     if i == a:
          break
     else:
       f.write(bb+ "\n")
f.close()



in "Enter products count" line in enter random number
(bb line makes random number and while loop makes list
with as much bb-random number as i entered in a= )
I need to write every time randomly generated number (bb line) in file ,
until while loop ends.
But i cant make it work . I have tried lots of ways but always got error .

Anybody know how to find solution to write line as much times in file , as many loops i have ?
Last edited by stranac on Tue Mar 25, 2014 5:20 pm, edited 1 time in total.
Reason: Added code tags. Locked.
varikasutaja
 
Posts: 1
Joined: Tue Mar 25, 2014 3:52 pm

Re: Write lines in loop problem

Postby stranac » Tue Mar 25, 2014 5:24 pm

We can't help if we don't know what the error is...
Please read this to learn how to post properly: viewtopic.php?t=145

Also, a while loop is not really the tool for this job, for would be much better suited.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1155
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: W3C [Linkcheck] and 3 guests