python simple file operations

def read_file():

  f = open("file.py",  "r", encoding='utf-6')     

  print (f.read ()) #-time read all the contents of the file, the file is large, will take up a lot of memory, read receiving a default int value, the default -1 is the full text, int value specifies the number of characters to read

  print (f.read (10)) # specified size is read, save some memory will thus read

  while True:

    z = f.read(10)

    print (z)

    if z is "":

      break

         f.close () # remember to close the file after opening, the release of resources

 

# With open help us to open the file to automatically close the file input and output streams.

def read_file (filename: str): # parameters here write filename: str, colon and data types, data types require explanation # this parameter is str, tell the caller when the function is called.

  with open(filename, 'r', encoding = 'utf-8') as f:

    lines = f.readlines () # line by line by line to read the file into a list, compare the memory footprint

       for line in lines:

      print (line) # Progressive Print

# F.readline a read-only line, take up less memory

def read_file(filename):

  with open("1.txt", 'r', encoding = 'utf-8' as f:

    line = f.readline()

    while line:

      line = f.readline

def write_file():

  with open("1.txt", 'w', enconding ="utf-8") as f:

  for i in range(100):

    f.write(str(i))

    f.flush () # The data memory buffer to disk to brush, or can only wait until the entire file write operations will write the entire file is complete. This will take up memory and untimely.

 

    

 

  

  

        

Guess you like

Origin www.cnblogs.com/laofang/p/12101962.html