Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read write mode python [duplicate]

Tags:

python

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

like image 970
Satyendra Avatar asked Nov 07 '12 08:11

Satyendra


People also ask

What is RW mode in Python?

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.

How do you duplicate a text file in Python?

The shutil. copy() method in Python is used to copy the content of the source file to destination file or directory.

Are both reading and writing possible after opening a file if so how?

'r+' opens the file for both reading and writing.


2 Answers

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
like image 135
ThiefMaster Avatar answered Oct 19 '22 18:10

ThiefMaster


From the doc:

r+: opens the file for both reading and writing

like image 31
Nicolas Avatar answered Oct 19 '22 17:10

Nicolas