Python IOError: File not open for reading

前端 未结 2 1396
[愿得一人]
[愿得一人] 2021-02-07 01:24

I get an error when I try to open a file in Python. Here is my code :

>>> import os.path
>>> os.path.isfile(\'/path/to/file/t1.txt\')
>>&         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-07 01:58

    You opened the file for writing by specifying the mode as 'w'; open the file for reading instead:

    open(path, 'r')
    

    'r' is the default, so it can be omitted. If you need to both read and write, use the + mode:

    open(path, 'w+')
    

    w+ opens the file for writing (truncates it to 0 bytes) but also lets you read from it. If you use r+ it is also opened for both reading and writing, but won't be truncated.

    If you are to use a dual-mode such as r+ or w+, you need to familiarize yourself with the .seek() method too, as using both reading and writing operations will move the current position in the file and you'll most likely want to move that current file position explicitly between such operations.

    See the documentation of the open() function for further details.

提交回复
热议问题