Hello!

I have some probs with this code, somehow it dont loop 10 times as it should, just one?
How do i make python use a testfil.txt that already exist? I dont want to remove the old data in the file just add new data to it? In this code, will i be able to change or remove the data in the file?

Im very new to python.


import random
n = 10
while n >= 0:
x = random.randrange(0,100,1)
testfil=file("testfil.txt","w")
rad=testfil.readline()
print>>testfil, x
testfil.close
n = n-1

help is welcomed! please

I dont want to remove the old data in the file just add new data to it?

Opening a file in write mode creates new file. You want to open in append mode. A Google for 'Python file append' will give all the info you want to know.

import random
testfil=file("testfil.txt","r")      ## opened for reading once only
fp_out = open('testfil.new', "a")
n = 10
for rad in testfil:
    if  n >= 0:
        x = random.randrange(0,100,1)
        print rad, x
        fp_out.write("%d\n" % (x))
        n = n-1
       
## file closed once only, not once for every loop
testfil.close()
fp_out.close()

Thanks for the help, i just found it a couple of hours ago, i have a follow up question.

Does the above code create individual "elements" in the textfil or is just text that you cant change or remove?

Thanks for the help, i just found it a couple of hours ago, i have a follow up question.

Does the above code create individual "elements" in the textfil or is just text that you cant change or remove?

I tried this code

import random
n = 10
for i in range(1):
while n >= 0:
x = random.randrange(0,100,1)
print x,
testfil=file("testfil.txt","a")
print>>testfil, x
testfil.close
n= n-1


for y in x: print y+1,

when i run the program i got this fault message:
Traceback (most recent call last):
File "D:\Python26\producer.py", line 25, in <module>
for y in x: print y+1,
TypeError: 'int' object is not iterable

is it because the file is closed?

random.randrange(0,100,1) returns an integer, so x will be an integer as you exit the while loop.

Please use code tags to enclose your code. This will preserve your all important block indentations

ok thanks, i think i have solved this one

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.