简体   繁体   中英

Should we open the file more than once to read it?

I have the following Python script. I noticed that I have to open() the file each time after a read() or a write() . Is that because the file closes automatically after such operations?

text_file = open('Text.txt','r')
print 'The file content BEFORE writing content:'
print text_file.read()
text_file = open('Text.txt','a')
text_file.write(' add this text to the file')
print 'The file content AFTER writing content:'
text_file = open('Text.txt','r')
print text_file.read()

Thanks.

Open in r+ mode and seek(0) :

with open('Text.txt', 'r+') as text_file:
    print 'The file content BEFORE writing content:'
    print text_file.read()
    text_file.write(' add this text to the file')
    print 'The file content AFTER writing content:'
    text_file.seek(0)
    print text_file.read()

prints:

The file content BEFORE writing content:
abc
The file content AFTER writing content:
abc add this text to the file

The docs have the details:

'+' open a disk file for updating (reading and writing)

seek() lets you move around in your file:

Change stream position.

Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. Values for whence are:

  • 0 -- start of stream (the default); offset should be zero or positive
  • 1 -- current stream position; offset may be negative
  • 2 -- end of stream; offset is usually negative

Return the new absolute position.

Is that because the file closes automatically after such operations?

No. The file is already opened and was not closed explicitly. But as you read through the file, the file position goes to the end of the file.

And you can not write a file if it is opened in readonly mode( r ). You have to open the file in write mode: (w/a/r+/wb) . Once read the file, you can move the file position using the seek() method of the file object.

Also, If you open a file using open function, you have to explicitly close the file. You can use:

with open('Text.txt', 'r') as text_file:
    # your code

This will close the file after the block of code is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM