Don't learn Python with the red head file of 2

  • 2020-04-02 14:13:33
  • OfStack

Properties of the file

A property is something that can be obtained from a file object.


>>> f = open("131.txt","a")
>>> f.name
'131.txt'
>>> f.mode      # Displays the mode in which the current file is open
'a'
>>> f.closed    # Whether the file is closed, and if so, return True ; If open, return False
False
>>> f.close()   # Close the file's built-in functions
>>> f.closed
True

About the status of the file

Many times, we need to get the state of a file (sometimes called a property, but the file property here is different from the file property above, but I think it's better to call it file state), such as the date of creation, the date of access, the date of modification, the size, and so on. In the OS module, there is a method to solve this problem:


>>> import os
>>> file_stat = os.stat("131.txt")      # Check the status of this file
>>> file_stat                           # The file status looks like this. From the following, you can guess a lot from the English words.
posix.stat_result(st_mode=33204, st_ino=5772566L, st_dev=2049L, st_nlink=1, st_uid=1000, st_gid=1000, st_size=69L, st_atime=1407897031, st_mtime=1407734600, st_ctime=1407734600) >>> file_stat.st_ctime                  # This is the file creation time
1407734600.0882277                      # Look at the time in a different way
>>> import time                        
>>> time.localtime(file_stat.st_ctime)  # I can see it better this time.
time.struct_time(tm_year=2014, tm_mon=8, tm_mday=11, tm_hour=13, tm_min=23, tm_sec=20, tm_wday=0, tm_yday=223, tm_isdst=0)

The above information about file state and file properties may be used to judge and manipulate certain aspects of a file. In particular, file properties. For example, when working with a file, we often need to determine whether the file has been closed or opened first, which requires the file.closed property.

Built-in functions for files


>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']
>>>

So many built-in functions, will not cover all, can only pick up the point to experiment.


>>> f = open("131.txt","r")
>>> f.read()
'My name is qiwsir.nMy website is qiwsir.github.ionAha,I like programn'
>>>

File.read () can read everything in a file. Note in particular that this returns a string and reads the entire contents of the file into memory. Just think, if the content is too much is not a bit sad? Sure, don't read big papers.


>>> contant = f.read()
>>> type(contant)
<type 'str'>

If the file is large, instead of reading it all at once, you can use readline line by line instead


>>> f = open("131.txt","r")
>>> f.readline()        # One row at a time, and then the pointer moves down
'My name is qiwsir.n'
>>> f.readline()        # Read it again and return one line
'My website is qiwsir.github.ion'
>>> f.readline()
'Aha,I like programn'
>>> f.readline()        # The last line is reached, read again, no error, return empty
''

This method, see an officer to feel too slow? Do you have anything to enjoy? Yes, please use readlines instead of using readlines. Notice the difference, this is a complex number, which means it's going to do more lines.


>>> f = open("131.txt","r")
>>> cont = f.readlines()
>>> cont
['My name is qiwsir.n', 'My website is qiwsir.github.ion', 'Aha,I like programn']
>>> type(cont)
<type 'list'>
>>> for line in cont:
...     print line
...
My name is qiwsir. My website is qiwsir.github.io Aha,I like program

From the experiment, we can see that readlines have the same thing as read, which is to read out the contents of the file once and store them in memory. However, there are some differences between readlines and read. Read returns the type STR, while readlines returns a list, with one element per line.

In print line, notice that each element in the list ends with a \n, so the printed result will have empty lines. The reason has already been introduced, those who forgot please roll back to the last lecture

However, it is important to remind the column bit that too large files do not have to be read into memory. For larger files, this is recommended:


>>> f = open("131.txt","r")
>>> f
<open file '131.txt', mode 'r' at 0xb757c230>
>>> type(f)
<type 'file'>
>>> for line in f:
...     print line
...
My name is qiwsir. My website is qiwsir.github.io Aha,I like program

These are all built-in functions and methods for reading files. In addition to reading, is to write. Write is to store content in a file. The built-in function used is write. However, to write to a file, also note the mode of opening the file, which can be w or a, depending on the situation.


>>> f = open("131.txt","a")     # Because this file already exists, I don't want to empty it and use append mode
>>> f.write("There is a baby.") # This sentence should go to the end of the file
>>> f.close()                   # Please note that after writing, must close the file in time. To actually write

See what it looks like:


>>> f = open("131.txt","r")
>>> for line in f.readlines():
...     print line
...
My name is qiwsir. My website is qiwsir.github.io Aha,I like program There is a baby.        # Sure enough, I added this row

These are the basic operations for files. In fact, far from knowing these files, interested readers can Google the module pickle, is a very useful thing.


Related articles: