G Y U L O G

title

파이썬 파일 입출력에 대해서 help 함수를 이용하고 싶은데 나오지 않죠?

 

아마 이런 에러코드를 뿜을 겁니다.

 

>>> help(read())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'read' is not defined
#===================================#
>>> help(write())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'write' is not defined

분명히 import 없이 사용가능한 함수인데 왜 그럴까 찾아보니, file타입이 파이썬 3에 오면서 삭제되었다는군요.

 

그대신 import sys를 할 경우 볼 수 있는 io모듈을 이용하여 파일 입출력 함수의 도움말을 찾을 수 있습니다.

 

import io

print(dir(io))
print(help(io.FileIO))

저는 이렇게 찾았습니다.

 

io는

import sys

print(dir(sys))

를 통해 찾았습니다.

 

dir로 어떤 메서드가 있는 지 보고, FileIO 가 적합해 보여서 이걸 help함수의 인수로 넣었습니다.

 

글 맨 끝에 FileIO에 대한 help 결과를 적어서 둘테니 열어보시면 됩니다.

 

read, write함수 말고 readline, seek 등의 여러 함수들에 대한 설명도 있으니 읽어보시면 좋습니다.

 

궁금했던 write, read에 대한 help입니다.

 

write(self, b, /)
 |      Write buffer b to file, return number of bytes written.
 |      
 |      Only makes one system call, so not all of the data may be written.
 |      The number of bytes actually written is returned.  In non-blocking mode,
 |      returns None if the write would block.
read(self, size=-1, /)
 |      Read at most size bytes, returned as bytes.
 |      
 |      Only makes one system call, so less data may be returned than requested.
 |      In non-blocking mode, returns None if no data is available.
 |      Return an empty bytes object at EOF.

read의 경우 아시다시피 EOF 반환이라고 적혀있네요. only makes one system call 이라는 부분도 눈에 들어옵니다.

 

더보기

class FileIO(_RawIOBase)

| FileIO(file, mode='r', closefd=True, opener=None)

|

| Open a file.

|

| The mode can be 'r' (default), 'w', 'x' or 'a' for reading,

| writing, exclusive creation or appending. The file will be created if it

| doesn't exist when opened for writing or appending; it will be truncated

| when opened for writing. A FileExistsError will be raised if it already

| exists when opened for creating. Opening a file for creating implies

| writing so this mode behaves in a similar way to 'w'.Add a '+' to the mode

| to allow simultaneous reading and writing. A custom opener can be used by

| passing a callable as *opener*. The underlying file descriptor for the file

| object is then obtained by calling opener with (*name*, *flags*).

| *opener* must return an open file descriptor (passing os.open as *opener*

| results in functionality similar to passing None).

|

| Method resolution order:

| FileIO

| _RawIOBase

| _IOBase

| builtins.object

|

| Methods defined here:

|

| __getattribute__(self, name, /)

| Return getattr(self, name).

|

| __getstate__(...)

|

| __init__(self, /, *args, **kwargs)

| Initialize self. See help(type(self)) for accurate signature.

|

| __repr__(self, /)

| Return repr(self).

|

| close(self, /)

| Close the file.

|

| A closed file cannot be used for further I/O operations. close() may be

| called more than once without error.

|

| fileno(self, /)

| Return the underlying file descriptor (an integer).

|

| isatty(self, /)

| True if the file is connected to a TTY device.

|

| read(self, size=-1, /)

| Read at most size bytes, returned as bytes.

|

| Only makes one system call, so less data may be returned than requested.

| In non-blocking mode, returns None if no data is available.

| Return an empty bytes object at EOF.

|

| readable(self, /)

| True if file was opened in a read mode.

|

| readall(self, /)

| Read all data from the file, returned as bytes.

|

| In non-blocking mode, returns as much as is immediately available,

| or None if no data is available. Return an empty bytes object at EOF.

|

| readinto(self, buffer, /)

| Same as RawIOBase.readinto().

|

| seek(self, pos, whence=0, /)

| Move to new file position and return the file position.

|

| Argument offset is a byte count. Optional argument whence defaults to

| SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values

| are SEEK_CUR or 1 (move relative to current position, positive or negative),

| and SEEK_END or 2 (move relative to end of file, usually negative, although

| many platforms allow seeking beyond the end of a file).

|

| Note that not all file objects are seekable.

|

| seekable(self, /)

| True if file supports random-access.

|

| tell(self, /)

| Current file position.

|

| Can raise OSError for non seekable files.

|

| truncate(self, size=None, /)

| Truncate the file to at most size bytes and return the truncated size.

|

| Size defaults to the current file position, as returned by tell().

| The current file position is changed to the value of size.

|

| writable(self, /)

| True if file was opened in a write mode.

|

| write(self, b, /)

| Write buffer b to file, return number of bytes written.

|

| Only makes one system call, so not all of the data may be written.

| The number of bytes actually written is returned. In non-blocking mode,

| returns None if the write would block.

|

| ----------------------------------------------------------------------

| Static methods defined here:

|

| __new__(*args, **kwargs) from builtins.type

| Create and return a new object. See help(type) for accurate signature.

|

| ----------------------------------------------------------------------

| Data descriptors defined here:

|

| closed

| True if the file is closed

|

| closefd

| True if the file descriptor will be closed by close().

|

| mode

| String giving the file mode

|

| ----------------------------------------------------------------------

| Methods inherited from _IOBase:

|

| __del__(...)

|

| __enter__(...)

|

| __exit__(...)

|

| __iter__(self, /)

| Implement iter(self).

|

| __next__(self, /)

| Implement next(self).

|

| flush(self, /)

| Flush write buffers, if applicable.

|

| This is not implemented for read-only and non-blocking streams.

|

| readline(self, size=-1, /)

| Read and return a line from the stream.

|

| If size is specified, at most size bytes will be read.

|

| The line terminator is always b'\n' for binary files; for text

| files, the newlines argument to open can be used to select the line

| terminator(s) recognized.

|

| readlines(self, hint=-1, /)

| Return a list of lines from the stream.

|

| hint can be specified to control the number of lines read: no more

| lines will be read if the total size (in bytes/characters) of all

| lines so far exceeds hint.

|

| writelines(self, lines, /)

|

| ----------------------------------------------------------------------

| Data descriptors inherited from _IOBase:

|

| __dict__

 

"댓글, 공감 버튼 한 번씩 누르고 가주시면 큰 힘이 됩니다"

공유하기

facebook twitter kakaoTalk kakaostory naver band