tehoo
tehoo

Reputation: 83

what is the difference between "r" and .read() in Python?

I want to open a text file and use split

Here is the code I wrote at first:

with open("test.txt","r") as file:
 file.split("\n")

and here is another code I wrote because the first code I wrote didn't work:

txt=open("test.txt")
file=txt.read()
file.split("\n")

what is the difference between "r" and .read()?

Upvotes: 0

Views: 7282

Answers (3)

Frank AK
Frank AK

Reputation: 1781

The r, You can think of it as the purpose of opening a file. if you open a file with r, and then you can't do write with the handler! You should got some error as :

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IOError: File not open for writing

read() just a way which you can got your data from file handler! there are also have readline() available.

Upvotes: 0

ubadub
ubadub

Reputation: 3880

read() is the actual function that does the reading of any "path-like object," returning a "file-like object" (this is due to the principle of duck typing). You can optionally pass it a parameter, which is a single character, indicating what "mode" to open the path-like object. Look at the signature for read():

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

You can see that the default mode is 'r', thus, if you do not specify a mode, it will default to 'r' anyways, so including 'r' as you did is generally redundant.

The documentation is here

Upvotes: 0

A Khalili
A Khalili

Reputation: 222

The .read() function is for reading data from a file; So the file should be in read mode and the read mode is 'r' that you asked.

So 'r'is Mode for File and .read() is a function for reading data.

Upvotes: 1

Related Questions