Python file operations

Source: Internet
Author: User

The program we write in Python is put into a hard disk for permanent storage, which involves the application to manipulate the hardware, but the program cannot manipulate the hardware directly, requiring the operating system as a mediator, i.e. the operating system encapsulates the hardware operation into a simple interface for use by the user/application. As a result, file operations operate on the virtual concept of the hard disk through an operating system provisioning application that allows users or applications to persist data by manipulating files.

first, let's briefly introduce an example :
 1  f = open ( " f:\pingguo.txt  , "  r  , encoding= "    Utf-8   ") #       Open the file, assign the file to a variable f  2  data = F.read () Reads the contents of the file  3  print   4  f.close () #   close file  
as can be seen from the simple example above, the variable F, in fact, is the variable f_obj,f_handler,f_h,fh, that is, the file handle The open () function is a built-in function of Python (which internally calls the Windows System command), and the process of manipulating the file can be summarized as:
1. Open file, generate file handle
2. Manipulating file Handles
3. Close file handle
Through the list, dictionaries and other additions and deletions, the file also has similar operations, but there are very different, then the file according to read, write, append and other operations. The first is the read operation: In Python, the read operation is ' R ', which is mode = ' R '. However, for R mode, mode can be written by default.

Read operations are usually described by several reading methods, the following hit.
1. Read all the contents of the file ()
1 1. Full read of the contents of the file reads  ()2 f = open ('f:\ poetry. txt', encoding='  utf_8'R')3 content = F.read ()  4print(content)5 f.close ()

The results shown are:

" " E:\python3.6.5\python.exe g:/pythonfile/week1/Knight plan/week_3/day_1/class content. py AoE level, Sarang singing songs on the river. East Sunrise West Rain, the road is heartless but sentient. Process finished with exit code 0"
2. Read (n) reads by character
1 f = open ('f:\ verse. txt''utf-8'r ' )2 content = F.read (3)print(content)4 F.close ()
# the output is: " " yangliuqing AoE level,   smell  
As can be seen from the output, in read mode, the data is read by character, where the last space in the first line also occupies one character.
3 Read content by line: ReadLine ()
1f = open ('f:\ poetry, txt', encoding='Utf-8', mode='R')2 Print(F.readline (). Strip ())3 Print(F.readline (). Strip ())4 Print(F.readline (). Strip ())5 Print(F.readline (). Strip ())6 Print(F.readline (). Strip ())7F.close ()

Results:

Yangliuqing AoE level, Sarang singing songs on the river. East Sunrise West Rain, the road is heartless but sentient.
Read only one line of code at a time, and if there is no strip () function, then each row reads a blank line and then reads the next line, when ReadLine () is more, will not error
4 reads by line and returns a list
 1  4 reads by row and returns a list  2  f = open ("  f:\ verse. txt  Span style= "COLOR: #800000" > ", Encoding="   Utf-8   ", Mode="  r   " )  3  content = F.readlines () #   [' yangliuqing aoe level, \ n ', ' Sarang ' singing on the river. \ n ', ' east of Sunrise in the West rain, \ n ', ' Tao is heartless but sentient. ']  4  print   (content)  5  f.close () 
The output is a list, each line of content represents an element, and each line has a newline character at the end .
5 for Loop
1 f = open ('f:\ poetry. txt', encoding='utf-8', mode='  R')2 for in F:3     Print (line) 4 F.close ()
"' Yangliuqing AoE level, Sarang singing songs on the river. East Sunrise West Rain, road is ruthless but

 

As you can see, the loop output is executed on each line of each row, with a blank line, in order to remove the empty row using the Line.strip () function, as follows:
1 f = open ('f:\ poetry. txt', encoding='utf-8', mode='  R')2 for in F:3     Print (Line.strip ()) 4 F.close ()

Generally in the case of large amounts of data processing, it is recommended to use a For loop, mainly in a large amount of data under the file, the other way to read the file all the data into memory, will result in memory space becomes larger, consumes memory, and for loop is to read the data row by line in memory, after each read a row is destroyed, Saves on memory consumption.

RB file operations usually with the B-letter, are related to non-text type files
# related to Text class Read method
1 f = open ('f:\ verse. txt', mode='rb')2 content = f.readlines ()3print(content)4 f.close ()
Bytes mode for reading, so encode = ' utf-8 ' is not required
# output results are output in bytes mode:
"' [B ' \xe6\x9d\xa8\xe6\x9f\xb3\xe9\x9d\x92\xe9\x9d\x92\xe6\xb1\x9f\xe6\xb0\xb4\xe5\xb9\xb3\xef '
B ' \xbc\x8c\r\n ', b ' \xe9\x97\xbb\xe9\x83\x8e\xe6\xb1\x9f\xe4\xb8\x8a\xe5\x94\xb1\xe6\xad\x8c '
B ' \xe5\xa3\xb0\xe3\x80\x82\r\n ', B ' \xe4\xb8\x9c\xe8\xbe\xb9\xe6\x97\xa5\xe5\x87\xba\xe8\
\xbf\xe8\xbe\xb9\xe9\x9b\xa8\xef\xbc\x8c\r\n ', B ' \xe9\x81\x93\xe6\x98\xaf\xe6\x97\xa0\xe6 '
B ' \x83\x85\xe5\x8d\xb4\xe6\x9c\x89\xe6\x83\x85\xe3\x80\x82 ' ...
Read files related to non-literal classes: such as reading pictures
1 f = open ('f:\ not. jpg', mode='rb')2 content = f.read ()3print(content)    #  B ' \xff\xd8\xff\xe0\ X00\x10jfif\x00\x01\x01\x00\x00h\x00h\x00\x00\xf ..... 4 F.close ()
Similarly, reading only part of the data using read (n)
1 f = open ('f: No. jpg', mode='rb')2 content = F.read (9)      #  B ' \xff\xd8\xff\xe0\x00\x10jfi '  mode, read by byte 3 Print (content) 4 F.close ()
r+ Read and write: Append after first reading
 1  f = open ( " f:\ verse. txt   ", Encoding="   Utf-8   ", Mode="  r+   " )  2  content = f.read (3"  3  print   4  f.write ( 666   "  )  5  f.close () 
The action is to read 3 characters in the file before the cursor moves to the contents of the file, and then add the content ' 666 '
1 f = open (' poetry. txt', encoding='utf-8', mode='  r+')2 f.write (' shenzhen Hello!  ')3 f.close ()
"Shenzhen Hello!" level, singing songs on the Sarang River. East Sunrise West Rain, the road is heartless but sentient. ‘‘‘

From the results, the direct write without reading causes the cursor to be overwritten directly from the beginning.

1 # Error 2 # f = open (' poetry. txt ', mode= ' RB ') 3 # # content = F.read (Ten) 4 # # Print (content) 5 # f.write (' 666 ') 6 # f.close ()
Write operations
U x
# If there are no files, create the file and then write the content
# If you have a file, clear the contents of the original file before writing the new content.
1 f = open (' poetry. txt', encoding='utf-8', mode='  w')2 f.write (' Shenzhen, Nanshan District ...  ')3 f.close ()
Wb
1f = open ('f:\ not. jpg', mode='RB')2Content = F.read ()#Save picture information to a variable3 Print(content)#b ' \xff\xd8\xff\xe0\x00\x10jfif ...4F1 = open ('No, 1.jpg .', mode='WB')5 f1.write (content)6 f.close ()7F1.close ()
Non-text files, first read out in bytes format (RB), and then write in bytes format (WB)
w+ Write Read
1f = open ('Poetry-txt', encoding='Utf-8', mode='w+')2F.write ('Shenzhen Nanshan District Xanadu ... ')#Clear Content First3F.seek (3)#move cursor position, is moved by byte, in Utf-8 mode, each text moves three bytes, if it is not a multiple of 3, then the error4Content =F.read ()5 Print(content)6F.close ()
Append a
When there is no file, the file is created and the content is written in
Append content directly to the last side of the file when there is a file
1 f = open ('t1.txt', encoding='utf-8', mode='  a')2 f.write ('\ n You are my little ya little apple ....  ')3 f.close ()
Other methods such as: AB A + a+b is not introduced here.
Other methods


Python file operations

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.