Reputation: 333
I am trying to append data to a file. Each line gets written inside a function. Below is a sample code based on my actual code:
a = 0
def data():
global a
a = int(raw_input('Enter value for a\n>'))
write()
def write():
f = open('path\\to\\file.txt', "a")
f.write('%s\n' % a)
f.close
proceed()
def proceed():
should = raw_input('Please press enter to continue or type in 0 to stop\n>')
if should == '0':
return
else:
data()
data()
When I run the code and give, for example, 1, 2 and 3
as values for a, this is how it gets written to the file:
3
2
1
But I want it to be written to the file this way:
1
2
3
What would be the right way to do that? How do I append a new line at the end of a file every time I run the write
function?
Upvotes: 1
Views: 2436
Reputation: 91
The proper way to implement your demands has been given by @Ukimiku.
As for why your code behaves like that, my opinion is here.
In fact, open a file with open('path','a')
will move the file pointer to the end of the file you open so that when you use write()
, you append something.
f = open('path\\to\\file.txt', "a")
print f.tell() #get the position of current file pointer
f.write('%s\n' % a)
Add print f.tell()
after you open file.txt. You will find every time you open it, the pointer position is always 0, which indicates that your write()
operation insert those numbers at the beginning of that file. This happened because of no closing. Those changes happen in memory and haven't been written to disk yet.
Upvotes: 1
Reputation: 618
Your program structure gives rise to a possibly very deep recursion (problem). Because in data(), you call write(), and in write() you call proceed(), and in proceed() you call data() again. Try to avoid this kind of structure. The following code avoids this problem, and is shorter:
def data():
while True:
a = int(raw_input('Enter value for a\n>'))
f.write(str(a) + '\n')
should = raw_input('Please press enter to continue or type in 0 to stop\n>')
if should == 0:
break
f = open('path\\to\\file.txt', "a")
data()
f.close()
Upvotes: 2