python-open 파일 처리 방법 소개

高洛峰
풀어 주다: 2017-03-20 10:31:26
원래의
1679명이 탐색했습니다.

python내장 함수open()을 사용하여 파일을 열고객체

구문

open(name[,mode[,bufsize]])
로그인 후 복사

name :파일 이름

mode: 파일 열기 모드 지정

r: 읽기 전용

w: 쓰기

a: 추가

r+, w+, a+는 입력 및 출력 작업을 동시에 지원합니다.

rb, wb+는 바이너리 모드로 열립니다.

bufsize: 출력 정의 캐시

0은 없음 출력 캐시

1은 버퍼 사용

음수는 시스템 기본 설정 사용

양수는 대략 지정된 크기의 버퍼 사용

#以只读方式打开text.txt文件,赋值给f1变量
>>> f1 = open('test.txt','r')

#查看f1数据类型
>>> type(f1)
<class &#39;_io.TextIOWrapper&#39;>

#读取文件内容,以字符串形式返回
>>> f1.read()
&#39;h1\nh2\nh3\nh4\nh5\nh6&#39;

#此时指针处于文件末尾,通过tell获取当前指针位置,通过seek重新指定指针位置
>>> f1.readline()
&#39;&#39;
>>> f1.tell()

>>> f1.seek(0)

#单行读取
>>> f1.readline()
&#39;h1\n&#39;

#读取余下所有行,以列表方式返回
>>> f1.readlines()
[&#39;h2\n&#39;, &#39;h3\n&#39;, &#39;h4\n&#39;, &#39;h5\n&#39;, &#39;h6&#39;]

#文件名
>>> f1.name
&#39;test.txt&#39;

#关闭文件
>>> f1.close()

#文件写入
f2 = open(&#39;test.txt&#39;,&#39;w+&#39;)
f2.write(&#39;hello&#39;)
f2.close()

#向文件追加内容
f3 = open(&#39;test.txt&#39;,&#39;a&#39;)
f3.write(&#39;hello&#39;)
f3.close()

#通过flush,将缓冲区内容写入文件
#write将字符串值写入文件
f3 = open(&#39;test.txt&#39;,&#39;w+&#39;)
for line in (i**2 for i in range(1,11)):
    f3.write(str(line)+&#39;\n&#39;)
f3.flush()
#f3.close()

#writelines将列表值写入文件
f3 = open(&#39;test.txt&#39;,&#39;w+&#39;)
lines = [&#39;11&#39;,&#39;22&#39;,&#39;33&#39;,&#39;44&#39;]
f3.writelines(lines)
f3.seek(0)
print(f3.readlines())
f3.close()
#执行结果:[&#39;11223344&#39;]

>>> f3.closed
True
>>> f3.mode
&#39;w+&#39;
>>> f3.encoding
&#39;cp936&#39;
로그인 후 복사
Help on TextIOWrapper object:class TextIOWrapper(_TextIOBase) |  Character and line based layer over a BufferedIOBase object, buffer. |  
 |  encoding gives the name of the encoding that the stream will be |  decoded or encoded with. It defaults to locale.getpreferredencoding(False). |  
 |  errors determines the strictness of encoding and decoding (see |  help(codecs.Codec) or the documentation for codecs.register) and
 |  defaults to "strict". |  
 |  newline controls how line endings are handled. It can be None, &#39;&#39;, |  &#39;\n&#39;, &#39;\r&#39;, and &#39;\r\n&#39;.  It works as follows: |  
 |  * On input, if newline is None, universal newlines mode is
 |    enabled. Lines in the input can end in &#39;\n&#39;, &#39;\r&#39;, or &#39;\r\n&#39;, and
 |    these are translated into &#39;\n&#39; before being returned to the |    caller. If it is &#39;&#39;, universal newline mode is enabled, but line |    endings are returned to the caller untranslated. If it has any of |    the other legal values, input lines are only terminated by the given |    string, and the line ending is returned to the caller untranslated. |  
 |  * On output, if newline is None, any &#39;\n&#39; characters written are |    translated to the system default line separator, os.linesep. If |    newline is &#39;&#39; or &#39;\n&#39;, no translation takes place. If newline is any |    of the other legal values, any &#39;\n&#39; characters written are translated |    to the given string. |  
 |  If line_buffering is True, a call to flush is implied when a call to |  write contains a newline character. |  
 |  Method resolution order: |      TextIOWrapper |      _TextIOBase |      _IOBase |      builtins.object |  
 |  Methods defined here: |  
 |  getstate(...) |  
 |  init(self, /, *args, **kwargs) |      Initialize self.  See help(type(self)) for accurate signature. |  
 |  new(*args, **kwargs) from builtins.type |      Create and return a new object.  See help(type) for accurate signature. |  
 |  next(self, /) |      Implement next(self). |  
 |  repr(self, /) |      Return repr(self). |  
 |  close(self, /) |      Flush and close the IO object. |      
 |      This method has no effect if the file is already closed. |  
 |  detach(self, /) |      Separate the underlying buffer from the TextIOBase and return it. |      
 |      After the underlying buffer has been detached, the TextIO is in an |      unusable state. |  
 |  fileno(self, /) |      Returns underlying file descriptor if one exists. |      
 |      OSError is raised if the IO object does not use a file descriptor. |  
 |  flush(self, /) |      Flush write buffers, if applicable. |      
 |      This is not implemented for read-only and non-blocking streams. |  
 |  isatty(self, /) |      Return whether this is an &#39;interactive&#39; stream. |      
 |      Return False if it can&#39;t be determined.
 |  
 |  read(self, size=-1, /) |      Read at most n characters from stream. |      
 |      Read from underlying buffer until we have n characters or we hit EOF. |      If n is negative or omitted, read until EOF. |  
 |  readable(self, /) |      Return whether object was opened for reading. |      
 |      If False, read() will raise OSError. |  
 |  readline(self, size=-1, /) |      Read until newline or EOF. |      
 |      Returns an empty string if EOF is hit immediately. |  
 |  seek(self, cookie, whence=0, /) |      Change stream position. |      
 |      Change the stream position to the given byte offset. The offset is
 |      interpreted relative to the position indicated by whence.  Values |      for whence are: |      
 |      * 0 -- start of stream (the default); offset should be zero or positive |      * 1 -- current stream position; offset may be negative |      * 2 -- end of stream; offset is usually negative |      
 |      Return the new absolute position. |  
 |  seekable(self, /) |      Return whether object supports random access. |      
 |      If False, seek(), tell() and truncate() will raise OSError. |      This method may need to do a test seek(). |  
 |  tell(self, /) |      Return current stream position. |  
 |  truncate(self, pos=None, /) |      Truncate file to size bytes. |      
 |      File pointer is left unchanged.  Size defaults to the current IO |      position as reported by tell().  Returns the new size. |  
 |  writable(self, /) |      Return whether object was opened for writing. |      
 |      If False, write() will raise OSError. |  
 |  write(self, text, /) |      Write string to stream. |      Returns the number of characters written (which is always equal to |      the length of the string). |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here: |  
 |  buffer |  
 |  closed |  
 |  encoding |      Encoding of the text stream. |      
 |      Subclasses should override. |  
 |  errors |      The error setting of the decoder or encoder. |      
 |      Subclasses should override. |  
 |  line_buffering |  
 |  name |  
 |  newlines |      Line endings translated so far. |      
 |      Only line endings translated during reading are considered. |      
 |      Subclasses should override. |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _IOBase: |  
 |  del(...) |  
 |  enter(...) |  
 |  exit(...) |  
 |  iter(self, /) |      Implement iter(self). |  
 |  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
로그인 후 복사

*with

파일을 연 후 닫는 것을 잊지 않도록 컨텍스트를 관리할 수 있습니다. with 코드 블록이 실행되면 파일 리소스가 내부적으로 자동으로 닫힙니다. 그리고 석방되었습니다.

아아아아


위 내용은 python-open 파일 처리 방법 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿