This article describes how to process python-open files. The python built-in function open () is used to open files and create file objects.
Syntax
open(name[,mode[,bufsize]])
Name: file name
Mode: specifies the file opening mode.
R: Read-only
W: Write
A: Attach
R +, w +, and a + support both input and output operations
Rb, wb + enabled in binary mode
Bufsize: defines the output cache.
0 indicates no output cache
1 indicates buffer
Negative number indicates that the system default settings are used.
Positive number indicates the buffer with an approximate specified size.
Open the text.txt file as a reader and assign the value to the f1 variable >>> f1 = open('test.txt ', 'r') # view the f1 data type >>> type (f1)
# Read the file content and return it as a string >>> f1.read () 'h1 \ h2\ NH \ nh5 \ nh6' # the pointer is at the end of the file, get the current pointer position through tell, and re-specify the pointer position through seek> f1.readline () ''> f1.tell ()> f1.seek (0) # reading a single row >>> f1.readline () 'h1 \ n' # read all the remaining rows and return them as a list >>> f1.readlines () ['h2 \ n ', 'h3 \ n', 'h4 \ n', 'h5 \ n', 'h6 '] # file name >>> f1.name'test.txt' # close the file >>> f1.close () # Writing f2 = open('test.txt ', 'W +') f2.write ('Hello') f2.close () # Appending content to the file f3 = open('test.txt ', 'A ') f3.write ('Hello') f3.close () # write the buffer content to a file through flush # write 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 write list values to the file f3 = open('test.txt ', 'W +') lines = ['11', '22', '33', '44'] f3.writelines (lines) f3.seek (0) print (f3.readlines () f3.close () # execution result: ['20140901'] >>> 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 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, '', | '\n', '\r', and '\r\n'. It works as follows: | | * On input, if newline is None, universal newlines mode is | enabled. Lines in the input can end in '\n', '\r', or '\r\n', and | these are translated into '\n' before being returned to the | caller. If it is '', 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 '\n' characters written are | 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 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 'interactive' stream. | | Return False if it can'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
*
To avoid forgetting to close a file after it is opened, you can manage the context. when the with code block is executed, the file resources are automatically closed and released internally.
with open("test.txt","a+") as f: f.write("hello world!")
The above is a detailed introduction to the python-open file processing method. For more information, see other related articles in the first PHP community!