top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Change a file type in Python?

+3 votes

When opening a file, you'd say whether you want to read or write to a file. This is fine, but say for example later on in the program I change my mind and I want to write to a file instead of reading it. Yes, I could just say 'r+w' when opening the file, but what if I don't know if I'm going to do both? What if I have the user decide, and then later on I let the user change this.

Is it possible to do so without opening the file again and using the same file object?

posted Nov 30, 2013 by Majula Joshi

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

In the general sense, no, but you may be able to abuse things terribly by calling __init__ on an existing object. The only advantage of that would be if you have multiple references to the file object, so normally don't - just close it and reopen. You can't change access/share mode on the file system without closing and reopening, so ultimately that's going to have to happen.

answer Dec 1, 2013 by Jagan Mishra
Similar Questions
0 votes

I need to write into a file for a project which will be evaluated on the basis of time. What is the fastest way to write 200 Mb of data, accumulated as a list into a file.

Presently I am using this:

with open('index.txt','w') as f:

where data is a list of strings which I want to dump into the index.txt file

+3 votes

If you use fread to read a file of unknown size with a set buffer size of say 500 bytes, when you get to the end of the file you are likely to read a stub of 500 bytes of info and the eof marker.

And fread will not read that block and set and oef that can be read with feof. That is how I understand, so we can either use fseek to discover the file size and fread accordingly or use fstat?

Is this the proper approach?

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.