1
f = open("test.txt",'r+')
print f.read();
f.write('\n\nI am carl wei.')
print f.read();
f.close()

but it's has a eeror:

Traceback (most recent call last):
File "C:\Users\carl.wei\workspace\Python\FileTest.py", line 9, in f.write('\n\nI am carl wei.') IOError: [Errno 0] Error

Carl
  • 251
  • 1
  • 4
  • 13
  • 1
    Hi, this is already explained here. http://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file – theAlse Feb 14 '14 at 07:31
  • related: [Python file operations](http://stackoverflow.com/q/11176724/4279) – jfs Feb 14 '14 at 08:13

1 Answers1

1

I don't know I got your question or not, but if you want to read a file and write it at the same time, you may like to check out This

But from my experience if you use the same file to write and read datas all the data will be erased and that might be trouble some in future, ergo you can simply make another file in the same directory and have some code like this:

original_file= open('test.txt','r')  # r when we only wanna read file
revised_file = open('test1.txt','w')  # w when u wanna write sth on the file        
for aline in original_file:      
    revised_file.write('I am carl wei.\n' )  # for writing your new data
                   
original_file.close()
revised_file.close()
alper
  • 2,919
  • 9
  • 53
  • 102
Prelude
  • 151
  • 1
  • 10