Ananay Sethi
Ananay Sethi

Reputation: 11

PyCharm on MacOS unable to handle files

I'm learning Python right now, and am trying to learn file handling using PyCharm CE on MacOS. While trying to open or create a new file, I get an error that goes something like this -

io.UnsupportedOperation: not readable

My code looks something like this:

import os             
print (os.path.abspath(os.curdir))

fhand = open("file1.rtf", "w")

for line in fhand:
    if line.startswith("from :") :
        line = line.strip()
        print(line)

How do I open a file and write something within it? And what is wrong with this code?

Upvotes: 1

Views: 193

Answers (1)

Micha
Micha

Reputation: 289

You opened the file in the wrong mode. This has nothing to do with PyCharm, but with your code :)

If you open a file in python (or most other programming languages), you have to specify, whether you want to read it or write it. You have more options than that, but let's keep it simple.

To do so, you use the second argument of the open() function, in your case "w", which stands for write.

If you want to read, change it to "r":

fhand = open("file1.rtf", "r")

If you want to read and write, you may use something like w+. To get an overview, you may find this diagram useful.

From the docs:

open() returns a file object, and is most commonly used with two arguments: open(filename, mode).

f = open('workfile', 'w')

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

Upvotes: 2

Related Questions