내장함수 - file(name[, mode[, buffering]])

2015. 7. 20. 10:58IT관련

반응형

https://docs.python.org/2/library/functions.html#file


file(name[, mode[, buffering]])

file object를 생성할 때 사용한다.


ModesDescription
rOpens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rbOpens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
wOpens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wbOpens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
aOpens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
abOpens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.


>>> f = file('test.py', 'r')

>>> f.read()

'print 42\n'

>>> f.write('sss')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IOError: File not open for writing

>>> f = file('test.py', 'r+')

>>> f.write('print 32\n')

>>> f.close()

>>> f = file('test.py', 'r')

>>> f.read()

'print 32\n'

>>> f.close()

>>> f = file('test.py', 'a')

>>> f.write('print 22\n')

>>> f.close()

>>> f = file('test.py', 'r')

>>> f.read()

'print 32\nprint 22\n'



반응형