Python built-in function open () for opening files and creating file objects
Grammar
Open (Name[,mode[,bufsize]])
Name: File name
Mode: Specifies the open mode of the file
R: Read-only
W: Write
A: Additional
R+,w+,a+ supports both input and output operations
rb,wb+ opens in binary mode
BufSize: Defining output caching
0 indicates no output cache
1 indicates the use of buffering
Negative numbers mean using system default settings
A positive number indicates a buffer with an approximate specified size
#以只读方式打开text. txt file, assign to f1 variable >>> f1 = open (' Test.txt ', ' R ') #查看f1数据类型 >>> type (F1) <class ' _io. Textiowrapper ' > #读取文件内容, returns the >>> f1.read () ' H1\nh2\nh3\nh4\nh5\nh6 ' #此时指针处于文件末尾 as a string, using tell to get the current pointer position, Reassign pointer position by seek >>> f1.readline () ' >>> F1.tell () >>> f1.seek (0) #单行读取 >>> F1.readline () ' h1\n ' #读取余下所有行, returned as a list >>> f1.readlines () [' h2\n ', ' h3\n ', ' h4\n ', ' h5\n ', ' h6 '] #文件名 >> > f1.name ' test.txt ' #关闭文件 >>> f1.close () #文件写入f2 = open (' Test.txt ', ' w+ ') f2.write (' Hello ') f2.close () # Append content to File F3 = Open (' Test.txt ', ' a ') f3.write (' Hello ') f3.close () #通过flush, writes the buffer contents to the file #write writes the string value to the file F3 = Open (' Test.txt ', ' w+ ') for line in (i**2 for I in range (1,11)): F3.write (str (line) + ' \ n ') F3.flush () #f3. Close () #writelines将列表值写入文件f3 = Open (' Test.txt ', ' w+ ') lines = [' One ', ' a ', ' ', ', ']f3.writelines ' (lines) f3.seek (0) print (f3.readlines ()) F3.close () # Execution result: [' 11223344 ']>>> f3.closedtrue>>> f3.mode ' w+ ' >>> f3.encoding ' cp936 '
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 would 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 is handled. It can be None, ', | ' \ n ', ' \ R ', and ' \ r \ n '. It works as follows: | | * on input, if newline are None, universal newlines mode is | Enabled. Lines in the input can end in ' \ n ', ' \ R ', or ' \ r \ n ', and | These is translated into ' \ n ' before being returned to the | Caller. If it is ", universal newline mode is enabled, but line | Endings is returned to the caller untranslated. If it has any of | The other legal values, input lines is terminated by the given | StringAnd the line ending are returned to the caller untranslated. | | * On output, if newline was None, any ' \ n ' characters written is | Translated to the system default line separator, Os.linesep. If | NewLine is ' or ' \ n ', no translation takes place. If NewLine is any | Of the other legal values, any ' \ n ' characters written is translated | to the given string. | | If line_buffering is True, a call to flush was 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 a effect if the file is already closed. | | Detach (self,/) | Separate the underlying buffer from the textiobase and return it. | | After the underlying buffer have 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 a file descriptor. | | Flush (self,/) | Flush write buffers, if applicable. | | This isn't implemented for read-only and non-blocking streams. | | Isatty (self,/) | Return whether this was an ' interactive ' stream. | | Return False If it can ' t be determined. | | Read (self, size=-1,/) | Read at the most n characters from stream. | | Read from underlying buffer until we had n characters or we hit EOF. | If n is negative or omitted, read until EOF. | | Readable (self,/) | REturn whether object is opened for reading. | | If False, read () would raise OSError. | | ReadLine (self, size=-1,/) | Read until newline or EOF. | | Returns an empty string if EOF are 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 is: | | * 0--start of stream (the default); Offset should be zero or positive | * 1--current stream position; Offset May 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 () would raise OSError. | This method is need to do a test seek (). | | Tell (self,/) | Return current stream position. | | Truncate (self, pos=none,/) | Truncate file to size bytes. | | File pointer is the left unchanged. Size defaults to the current IO | Position as reported by Tell (). Returns the new size. | | Writable (self,/) | Return whether object is opened for writing. | | If False, write () would 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 specified to control the number of lines Read:no more | Lines would 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
To avoid forgetting to close after opening a file, you can manage the context and automatically close and release the file resource when the with code block finishes executing.
With open ("Test.txt", "A +") as F: f.write ("Hello world!")