twseewx
twseewx

Reputation: 332

Can you write to a text file and then read from that same text file in the same program?

Basically I want to be able to calculate a parameter store it was a text file then read it back in later in the program.

Upvotes: 0

Views: 356

Answers (3)

bconstanzo
bconstanzo

Reputation: 576

Also, you could open a file for reading AND writing, using:

fd = open(myfile, "r+")

However, you must be very careful, since every operation, either read or write, changes the pointer position, so you may need to use fd.seek to make sure you're placed in the right position where you want to read or write.

Also, keep in mind that your file becomes a sort of memory mapped string(*) that sometimes syncs with the disk. If you want to save changes at a specific point, you must use fd.flush and os.fsync(fd) to efectively commit the changes to disk without closing the file.

All in all, I'd say its better to stick to one mode of operation and then closing the file and opening again, unless there's a very good reason to have read/write available without switching modes.

* There's also a module for memory mapped files, but I think thats way beyond what you were asking.

Upvotes: 0

apomene
apomene

Reputation: 14389

You need to use close() before changing mode (read / write):

def MyWrite(myfile):
    file = open(myfile, "w")    
    file.write("hello world in the new file\n")   
    file.close()

def MyRead(myfile):
    file = open(myfile, "r")
    file.read()
    file.close()

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117951

myFile = 'example.txt'

Using with will automatically close the file when you leave that structure

# perform your writing
with open(myFile, 'w') as f:
    f.write('some stuff')

# doing other work
# more code

# perform your reading
with open(myFile, 'r') as f:
    data = f.read()
    # do stuff with data

Upvotes: 2

Related Questions