Reputation: 361
What is the difference between:
with open('PHANTOM_PAIN_SPOILERS.txt') as temp:
print(temp.read())
...and:
with open('PHANTOM_PAIN_SPOILERS.txt','r') as temp:
print(temp.read())
To my understanding, the second argument 'r'
for the open()
is essentially telling the system to read the file after opening it, which seems to me that it should make .read()
redundant but if I attempt to print temp print(temp)
in the second example, I end up with something similar to: <_io.TextIOWrapper name='PHANTOM_PAIN_SPOILERS.txt' mode='r' encoding='cp1252'>
So what was the point of specifying 'r' in the first place if it doesn't seem to do anything in these instances?
Upvotes: 3
Views: 15650
Reputation: 1618
Opening and reading files are different operations.
A file is opened as a first step in reading from it or writing to it. By default, the open()
call accesses the file in read mode. Specifying 'r'
as the second argument is just explicitly doing the same thing. (Specifying 'w'
opens the file in write mode.)
Once the file is open, it can be read in one big chunk (such as your code does), a line at a time, a byte at a time or more complex schemes using different read operations.
Upvotes: 3
Reputation: 76297
There are three different things here:
Your statement:
To my understanding, the second argument 'r' for the open() is essentially telling the system to read the file after opening it
is not quite correct. The 'r'
indicates that you wish to open the file in read mode; it does not read anything in itself. You can also read a file that is opened in other modes, incidentally.
The open
function takes a mode string with a default value of 'r'
, so omitting this parameter yields the same thing.
Upvotes: 4