16

Possible Duplicate:
python open built-in function: difference between modes a, a+, w, w+, and r+?

try:
    f = open("file.txt", "r")
    try:
        string = f.read()
        line = f.readline()
        lines = f.readlines()
    finally:
        f.close()
except IOError:
    pass


try:
    f = open("file.txt", "w")
    try:
        f.write('blah') # Write a string to a file
        f.writelines(lines) # Write a sequence of strings to a file
    finally:
        f.close()
except IOError:
    pass

Hi,

this is mode which i can read and write file but i want to open file once and perform both read and write operation in python

Community
  • 1
  • 1
Satyendra
  • 215
  • 1
  • 3
  • 6

2 Answers2

36

Like in any other programming languages you can open a file in r+, w+ and a+ modes.

  • r+ opens for reading and writing (no truncating, file pointer at the beginning)
  • w+ opens for writing (and thus truncates the file) and reading
  • a+ opens for appending (writing without truncating, only at the end of the file, and the file pointer is at the end of the file) and reading
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
12

From the doc:

r+: opens the file for both reading and writing

Nicolas
  • 5,583
  • 1
  • 25
  • 37
  • thanks but when i used r+ its appending file, i don't want to append – Satyendra Nov 07 '12 at 08:18
  • 9
    @Styendra you need to use f.seek(0) before the call to f.write() (f is the opened file object) otherwise f.read() will leave the position counter at the end of the file and that's where f.write() will pick up. – andreb Aug 14 '13 at 02:19