python learning-input and output of files

Keywords: Fragment Python

Input and output of files

File: The simplest type of data persistence is called flat file. It is just a byte stream under the name of a file, reading data from a file into memory, and then writing it from memory to a file.

Before reading a file, you need to open it, then you can call a function to read and write data, and finally you need to close the file.

fileobj = open(filename,mode)

fileobj is the file object returned by open();

filename is the string name of the file;

Modes are strings that specify file types and operations;

The first letter of mode indicates the operation on it:

r. Representation of reading patterns

w Represents write mode. If the file does not exist, it is created, and if it exists, it rewrites the new content.

x. Create and write a new file in the absence of a file

A) Indicates that if a file exists, it is appended to the end of the file.

The second letter of mode is the file type:

t (or omitted) represents the text type

b) Represents binary files

Write files using write()

>>>poem="""There was a young lady named Bright,\
      whose speed was far faster than light;\
      She started one day \
      In a relative way,\
      And returned on the previous night."""

>>> len(poem)
167
>>> fout = open('relativity','wt')  #Files are placed by default in the root directory of python D: python 3
>>> fout.write(poem)
167
>>> fout.close()
>>> fout = open('relativity1','wt')
>>> print(poem,file=fout)    # 169 print() adds spaces after each parameter by default and newlines at the end of each line. It adds a newline by default in file relativity 1.
>>> fout.close()

Use the following parameters to ensure that print() and write() have the same output:

sep separator: default is a space‘‘

end End Character: The default is a newline character' n'

>>> fout = open('relativity2','wt')
>>> print(poem,file=fout,sep='',end='')  #167
>>> fout.close()
>>> 

If the source string is very large, the data can be partitioned until all characters are written:

>>> fout = open('relativity3','wt')
>>> size = len(poem)
>>> offset = 0
>>> chunk = 100
>>> while True:
        if offset > size:
            break
        fout.write(poem[offset:offset+chunk])
        offset+=chunk
100
67
>>> fout.close()

If the'relativity'file already exists, schema x can be used to avoid rewriting the file, and an exception handling can be added:

>>> try:
      fout = open('relativity','xt')
      fout.write('stomp stomp stomp')
   except FileExistsError:
      print('relativity already exists!. That was a close one.')

Use read(), readline(), or readlines() to read text files

>>> fin = open('relativity','rt')
>>> poem = fin.read()
>>> fin.close()
>>> len(poem)
167
>>> 

The maximum number of read characters can be set to limit the size of the read() function returned at one time, and then each block is spliced into the original string.

>>> poem=''
>>> fin = open('relativity','rt')
>>> chunk = 100
>>> while True:
         fragment = fin.read(chunk)  #Read remembers where it has been read
         if not fragment:  # After reading the end of the file, calling read() again returns an empty string ('), and the if not fragment condition is judged to be False.
                   break
         poem += fragment

>>> fin.close()
>>> len(poem)
167

You can also use readline() to read one line of a file at a time and splice each line into the original string poem:

>>> poem = ''
>>> fin = open('relativity','rt')
>>> while True:
         line = fin.readline() #For a text file, even empty lines have a character length (newline characters'n')
         if not line:  #When line is not empty, return True. When the file is read out, readline() returns empty string and False.
                   break
         poem += line
>>> fin.close()
>>> len(poem)
167

The easiest way to read a text file is to use an iterator, which returns one line at a time.

>>> poem = ''
>>> fin = open('relativity','rt')
>>> for line in fin:
         poem += line
>>> fin.close()
>>> len(poem)
167
>>> 

The function readlines() reads one line at a time and returns a list of single-line strings.

Use write() to write binary files

If the file mode string contains'b', the file opens in binary mode, in which case bytes are read and written instead of strings.

>>> bdata = bytes(range(0,256))
>>> len(bdata)
256
>>> fout = open('bfile','wb')
>>> fout.write(bdata)
256
>>> fout.close()

Use read() to read binary files

>>> fin = open('bfile','rb')
>>> bdata = fin.read()
>>> len(bdata)
256
>>> fin.close()

Automatically close files with with

Forget to close the open file, the function will be closed at the end. Python's context manager cleans up some resources, such as open files, and should force all remaining write operations to complete before closing the files. It takes the form of: with expression as variable:

>>> with open('relativity','wt') as fout:
        fout.write(poem)

After completing the context manager's code, the file is automatically closed

Use seek() to change position

The function tell() returns the byte offset from the beginning of the file, and the function seek() allows you to jump to the location of other byte offsets in the file.

>>> fin = open('bfile','rb')
>>> fin.tell()
0
>>> fin.seek(255)
255

Call the function seek():seek (offset,origin) with the second parameter

If origin equals 0 (default is 0), offset bytes from the beginning;

If origin equals 1, offset bytes from the current location;

If origin equals 2, offset bytes from the end.

These values are also defined in the standard os module:

>>> os.SEEK_SET
0
>>> os.SEEK_CUR
1
>>> os.SEEK_END
2

Posted by chowdary on Mon, 15 Jul 2019 15:07:50 -0700