Python path (nineth) Python file operation

Source: Internet
Author: User
Tags readline throw exception

One, the operation of the file

File handle = open (' File path + filename ', ' mode ')

Example

f = open ("Test.txt", "r", encoding = "Utf-8")

  

Analysis: Because Python files and test.txt files are in the same folder, you do not need to write the absolute path of test

If you want to write an absolute path, you can write this

f = open (file = "D:/python/test.txt", "r", encoding = "Utf-8")

  

There are several modes of File open mode:

1. Open mode of text file

"R", read-only mode "default mode, file must exist, not present, throw exception"

"W", write-only mode "unreadable; not exist" created; empty content "

"A", append only write mode "unreadable; not exist" create; append content only "

is to open the file in binary mode, read the content is byte type, write also need to provide byte type, cannot specify encoding

"+" means you can read and write a file at the same time

"r+", read and write "readable, writable"

"w+", write "readable, writable"

"A +", read "readable, writable"

2, readable (), writable ()

Readable () determines whether the file is readable, returns TRUE or FALSE,

Writable () Determines whether the file is writable, returns TRUE or FALSE,

Example

F.readable ()

F.writable ()

3. Read (), ReadLine (), ReadLines ()

F.read () #读取所有内容, the cursor moves to the end of the file

F.readline () #读取一行内容, the cursor moves to the beginning of the second

F.readlines () #读取每一行内容, stored in the list

4. Write (), Writelines ()

Write () to write to the string, Writelines () to write to the list

  F.write (' 1111\n222\n ') #针对文本模式的写, need to write their own newline character  f.write (' 1111\n222\n '. Encode (' Utf-8 ')) #针对b模式的写, you need to write the line break  F.writelines ([' 333\n ', ' 444\n ']) #文件模式  f.writelines ([bytes (' 333\n ', encoding= ' utf-8 '), ' 444\n '. Encode (' Utf-8 ') ]) #b模式

  

5, F.close () #关闭文件f. Closed () #查看文件是否关闭

After opening the file with the open method, you must close the file with F.close ()

The file must be closed after it is used because the file object consumes the resources of the operating system, and the number of files that the operating system can open at the same time is limited.

F.closed () #查看文件是否关闭, returns TRUE or False

6, with open as F opening method

This way of opening the file without writing f.closed close the file

Example

  With open ('/path/to/file ', ' R ') as F: with    

  

7, for non-text files, we can only use B mode

Non-text File open mode, only use B mode, "B" means to operate in bytes (and all files are also stored in bytes, using this mode regardless of the text file character encoding, picture file JGP format, video file avi format, b mode can be used across platforms)

"RB"

"WB"

"AB"

f = open ("test.py", "RB")

Analysis: Note that this can not be added, encoding = "Utf-8", because this is opened in binary mode, no need to set the open encoding mode

Example

  f = open ("test.py", "RB")  data = F.read ()  print (data)

  

test.py File Contents:

Output

B ' "111" \ r \ n "2222" \ r \ n "3333" \r\n\xe4\xbd\xa0\xe5\xa5\xbd '

  

Analysis: here \ r \ n is the line break of Windows platform, starting with B represents the output is byte form

Here \XE4\XBD\XA0\XE5\XA5\XBD ' stands for kanji

  f = open ("test.py", "RB")  data = F.read ()  Print (Data.decode ("Utf-8"))

  

Output results

"111" "2222" "3333" Hello

  

Analysis: Here in the test.py file storage with the Utf-8 storage, in the print output when the "Utf-8" to decode the output results.

when opened in B, the content read is a byte type, and a byte type is required for writing, and encoding cannot be specified

Example 2

f = open ("test11.py", "WB") F.write ("111\n") F.close ()

  

Output: Error, indicating that a byte is required here, rather than a string form, where the write must be written in bytes

can be changed to

  f = open ("test11.py", "WB")  F.write (bytes ("111\n", encoding= "Utf-8"))  F.close ()

  

Analysis: Here it is possible to write the string "111\n" to the file, where bytes () must specify a code.

or encode the string directly without the bytes () method

  

8, F.encoding

The encoding to take the file open

Example

  
  f = open ("test11.py", "W", encoding= "GBK")  f.write ("222\n")  f.close ()  print (f.encoding)

  

Output

Gbk

  

Analysis: Here is the file open code, that is, the code in the Open statement, and the actual encoding of the source file regardless.

9, F.flush (), F.tell ()

F.flush () immediately brush the contents of the file from memory to the hard disk, here need to use command prompt operation, in the Pycharm will write directly to the hard disk, do not need to flush ()

F.tell () Gets the position where the current cursor is located

10. Cursor movement within the file

Read (3):

A, when the file is opened in text mode, represents reading 3 characters

b, when the file is opened in B mode, the delegate reads 3 bytes

Read () reads the entire file by default

The rest of the files within the cursor movement are in bytes such as Seek,tell,truncate

Example

Test.txt File Contents

  
  f = open ("Test.txt", "RB")  data = F.read (6)  f.close ()  print (data)

  

Output results

B ' 111\r\n2 '

  

Analysis: Here the 111 count 3 bytes, \ r \ n 2 bytes, 2 count 1 bytes, here is the B mode, in bytes to calculate, here can not specify the encoding can not write encoding = "XX", otherwise will error

Example 2

The file content is the same as above

  
  f = open ("Test.txt", "r+", encoding= "Utf-8")  data = F.read (6)  f.close ()  print (data)

  

Output results

11122

  

Analysis: This is the text mode, where 111 is counted 3 characters, line break \ r \ n is a character, 22 is 2 characters, a total of 6 characters.

11. Seek ()

Seek () moves the file cursor to the specified position.

Seek () syntax

  F.seek (offset[, whence])

Offset is the number of bytes moved, whence has 0,1,2 three modes, 0 for the file start, 1 for the current position, 2 for the end of the file count, the default is 0. Of these, 1 and 2 must be done in B mode, but regardless of which mode is moved in bytes, the line break under Widnows system represents a 2 byte size (\ r \ n).

Example

Test.txt File Contents

  
  f = open ("Test.txt", "r+", encoding= "Utf-8")  F.seek (3,0)  data = F.read ()  f.close ()  print (data)

  

Output results

222333 Hello 444aaabbbccc555

  

Example 2

The file content is the same as above

  
  f = open ("Test.txt", "RB")  F.seek (5)  F.seek (11,1)  print (F.tell ())  ?  data = F.read ()  f.close ()  print (data)

  

Output results

16b ' \xbd\xa0\xe5\xa5\xbd\r\n444\r\naaa\r\nbbb\r\nccc\r\n555 '

  

Analysis

Here is the binary open, 111 is counted 3 bytes, followed by an invisible \ r \ n newline character, so the position of seek (5) is the last of the first row

Seek (11,1) is to continue to move the cursor from the current position, that is, 222\r\n counts 5 bytes, the same 333\r\n counts 5 bytes, "Hello" (the text file is utf-8 encoded) 6 bytes, so only take "you" the word of the first byte of 3 bytes, The cursor moves to your first byte, so the last output is \xbd\xa0\xe5\xa5\xbd a total of 5 bytes.

Note that the cursor operation here is not valid by using the Seek () method and moving the cursor directly with the mouse.

Example 3

File contents

  
  f = open ("Test.txt", "RB")  offs = -20 while  True:      f.seek (offs,2)      data = F.readlines ()      If Len (data) & Gt 1:          print ("The last line of the file is%s"%data[-1].decode ("Utf-8"))          Breakf = open ("Test.txt", "RB")  offs = -20 while  True:      f.seek (offs,2)      data = F.readlines ()      If Len (data) > 1:          print ("The last line of the file is%s"%data[-1]. Decode ("Utf-8"))          break  ?

  

The goal here is to enter the last line without knowing how many bytes a row is

Output results

The last line of the file is 2018-04-15 Nicholas studied for 520 minutes.

Analysis: Seek ( -20,2) is calculated from the last beginning of the file and must be done in B mode.

12, truncate ()

truncate () The Widnows method is used to truncate from the beginning of a file, truncate the file to size bytes, no size to truncate from the current location, and all bytes after truncation are deleted, where the line break under the system is 2 bytes in size.

Example

File contents

  
  f = open ("Test.txt", "r+")  F.truncate (Ten)  data = F.read ()  print (data)

  

Output results

111aaa

  

Analysis: Here is calculated in bytes, 111 counts 3 bytes, followed by a newline character 2 bytes, so here Intercept 111AAA and the following 2 newline characters, a total of 10 bytes.

Python path (nineth) Python file operation

Related Article

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.