7. open files, read/write operations, with methods, common functions of files,

Source: Internet
Author: User

7. open files, read/write operations, with methods, common functions of files,
Open the file:

In python3, the function to open a file is:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
 
Parameter description:
File -- file name
Mode-open mode, default read-only mode
Buffering -- if the buffering value is set to 0, no storage will be available. If the buffering value is set to 1, the row is stored when the file is accessed. If the buffering value is set to an integer greater than 1, it indicates the buffer size of the storage zone. If the value is negative, the buffer size in the storage area is the default value.
Encoding-encoding of open files
Mode introduction:

R: Read-only mode (default)

W: Write-only mode. If the file does not exist, it is created. If yes, the written data overwrites the original data.

B: Binary Mode

T: text mode

+: Writable and readable Mode

A: append mode. If the file exists, the file Pointer Points to the end of the file (append data). If the file does not exist, it is created.

R +: Read append mode. read first and then append

W +: Write-and-Read mode. First writing means that the original content is lost and then reading.

 

 

 

  • If an object contains non-ascll characters, encoding must be used; otherwise, an exception is thrown:

Print ("r ". center (50, '-') f = open ("file.txt", encoding = "UTF-8") print (f. read () f. close () ----------------- running result: mysasaaafsafsa (Chinese)

 

The file must be closed after use: file pointer. close ()

 

File Operations:

 

Read operation:

Read the file content as follows:

  • Reads () reads all the content
Print ("r ". center (50, '-') f = open ("file.txt", encoding = "UTF-8") print (f. read () f. close () --------------------------- running result: mysasaaafsafsa Chinese gourd doll
  • Readline () is used to read a row.
Print ("r ". center (50, '-') f = open ("file.txt", encoding = "UTF-8") print (f. readline () f. close () ----------- running result: my
  • Readlines () is to read all the content and organize it into a list.
Print ("r ". center (50, '-') f = open ("file.txt", encoding = "UTF-8") print (f. readlines () f. close () ------------------------ r --------------------- running result: ['my \ n', 'sas \ n', 'aaa \ n', 'fsafsa \ n', 'Chinese \ n ', 'Chinese \ n', 'gourd doll \ n', '\ n']

 

  • The r + mode determines the pointer position based on the read content.
print("r".center(50,'-'))f=open("file.txt","r+",encoding="utf-8")# print(f.readline())f.write("hello mike")f.close()

Result:

 

print("r".center(50,'-'))f=open("file.txt","r+",encoding="utf-8")print(f.readline())f.write("hello mike")f.close()

New results:

 

 

 

 

Write operation:
  • Write (): write a string to a file.
Myfile = open ("myfile1", "wb") myfile. write (B "nnnnnn") myfile. write ("my gourd doll ". encode ("UTF-8") myfile. close ()
  • Writelines (iteratable object) writes an iteratable object to a file
myfile=open("myfile1","wb")myfile.write(b"nnnnnn")myfile.writelines([b'1',b'2',b'3',b'4'])myfile.close()
  • When you need to read the data immediately after writing the data, use w + and set the file pointer back to the file header:
myfile=open("myfile1","wb+")myfile.write(b"nnnnnn")myfile.seek(0)print(myfile.read())myfile.close()
      • If you want to read a specific location, you can use variables to record the location.
Myfile = open ("myfile1", "wb +") myfile. write (B "1 nnnnnn") site = myfile. tell () myfile. write (B "2 nnnnnn") myfile. seek (site) # Read the last print (myfile. read () myfile. close ()
With:
  • To conveniently close a file, python adds the with function. After the with body is executed, the opened file is automatically closed:
With open ("file.txt", "r +", encoding = "UTF-8") as f: # f. close () print (f. tell () f. write ("King Kong") for line in f: print (line, end = "")
  • You can open multiple files at the same time:
with open("file.txt",'r') as f ,\open("file.new",'r') as m:    print(f.read(),m.read())
Common file functions:

File. close (): close the file. After the file is closed, you cannot read or write the file.

 

File. seek (offset [, whence]): sets the current position of the file.

File. tell (): returns the current location of the file.

Myfile = open ("myfile1", "wb +") myfile. write (B "1 nnnnnn") site = myfile. tell () myfile. write (B "2 nnnnnn") myfile. seek (site) # Read the last print (myfile. read () myfile. close ()

File. flush (): refresh the file's internal buffer and immediately write the data in the internal buffer to the file, because the file is not immediately loaded.

import timemyfile=open("myfile1","wb+")myfile.write(b"1nnnnnn")time.sleep(10)# myfile.flush()myfile.write(b"2nnnnnn")myfile.close()

The above code will not write "1nnnnnnnn2nnnnnn" at a time until the program runs successfully"

import timemyfile=open("myfile1","wb+")myfile.write(b"1nnnnnn")myfile.flush()time.sleep(10)myfile.write(b"2nnnnnn")myfile.close()

The above Code shows that "1nnnnnn" has been written before the program sleep"

 

 

File. truncate ([size]): captures a file, starting from the beginning of the file to the specified location, and overwrites the original file.

File Content:

Print ("r ". center (50, '-') f = open ("file.txt", "r +", encoding = "UTF-8") print (f. readline () print ("---- truncate () -------") print (f. tell () m = f. tell () f. truncate (m) # content is truncated from 0 to the specified position, regardless of the current cursor position f. close ()

 

After execution, the file content:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.