Python learning: 7. File operation

Source: Internet
Author: User

File operations

We have heard a problem, the elephant into the refrigerator divided into three steps: 1, open the refrigerator door, 2, put the elephant in, 3, close the refrigerator door. The steps of the Python file operation that we're going to talk about today are like steps to put an elephant into a refrigerator.

Basic steps for manipulating files using Python:

    • Open File
    • Manipulating the contents of a file (reading file information, writing information to a file, etc.)
    • Close File
First, open the file

In the introduction to the built-in function of the previous article, we mentioned the Open function, which is the function of opening a file.

Format One

File handle = open (file path, open format, encoding)

When you open a file, you specify the path to the file and how to open the file, and you can get the file handle after it is opened, such as after you manipulate the file through this file handle.

f = open ("c:/asd.txt","R", encode='utf-8 ')    # Open the Asd.txt file under C disk date = F.read ()    # Read file contents f.close ()    # Close File  Print(date)    # output file contents

Format Two

With open (file path, open format, encoding), use this open file to close the file without using close (), because use this with automatic file close, but this need your file operation is in the code block, attention indentation.

With open ("c:/asd.txt", encoding='utf-8') as F:    = f.read ()print(data)

Various formats for opening files

When opening a file, you need to specify the file path and how to open the file, and then you can get the file
A handle, such as a handle to the file, is then manipulated by this file handle.
The Open modes are:

R, read-only file, "default" W, write-only file, "unreadable, not present" created; empty content "x, write-only file," unreadable, no creation, presence error "A, append mode," unreadable, nonexistent creation, existing only append content "

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

r+, read and write "readable, writable" W+, read "Readable, writable" x+, read "Readable, writable" a+, read "readable, writable"

"B" means to operate in bytes

RB or r+BWB or W+BxB or W+bab or a+b

When opened in B, the content read is a byte type, and a byte type is written to write.

Second, the contents of the operation of the file

Open a file with a generic format

1, when using the read-only format to open the file, file write will be error.

2. When the file is opened using the write format, the original content is purged and the content is re-written.

f = open ("asd","w")# clears the contents of the original file F.write ("asd")# re-write f.close ()

3, use write-only mode to open the file, no files are created, there are files when the error.

Then we use the previous command again, there will be an error, because the file exists.

4, Append mode open the file, when the file does not exist when the file is created, when the file exists at the end of the file to append content.

f = open ("asd","a")# does not exist created, there is an append f.write ( " ASD " ) F.close ()

Open a file using byte format

1. read-only format

f = open ("asd","RB")# is read in bytes when opened here, So there is no need to add encoding= "utf-8"data = f.read ()  f.close ()print(data) output: <class'bytes'>

2. Write-only format

f = open ("asd","wb"= f.write (bytes ("  China " "utf-8")f.close ()    # write in byte mode , you need to convert the string to bytes
internal encoding mechanism for two open methods

Normal format

Python internally converts 010101 to a string (because it is essentially 0101 in the hard disk, so it is 0101 when reading the data, and when it is open normally, The byte is automatically converted to a string by default using Utf-8, and in the go string is what encoding format we can specify to convert to a string).

010101======>python interpreter (converted to string) =====> programmer sees

BYTE format

Bytes Open when the bytes directly to the programmer, there is no compile process, so you cannot add encoding = "" In You write is, if you write a string, you need to convert the string to 010101, otherwise it will error because the byte mode is opened without the compilation process, Storage is not automatically compiled into 0101 so you need to do it yourself. The string is converted to byte f.write (bytes ("China", encoding = "Utf-8") to save.

010101======> programmers See

Example

Use byte format to read the file, the file is originally stored in the "China".

 f = open ( " ASD   ", "  RB   " ) data  = F.read () f.close ()  print   (data) data1  = str (data,encoding = "  utf-8   " "  #   If you're storing utf-8 in Python, If you write in Notepad you may need to use GBK  print   (data1) output: b   " \xe4\xb8\xad\xe5\x9b\xbd   "  China  

The file is written in byte format, or "China" is stored in the file.

f = open ("asd","wb"" China " = Bytes (str_a,encoding="utf-8") f.write (bytes_a)  Print (bytes_a) f.close () output result: b ' \XE4\XB8\XAD\XE5\X9B\XBD '

Input and output using the general format is a string, using byte format input and output are bytes, when we use the general does not use byte format for file read and write.

Internal pointer issues for read and write files

f = open ("World.txt","r+", encoding='Utf-8') Data=F.read ()Print(Type (data), data) F.write ("Earth Village") A=F.read ()Print(Type (a), a)#here the output is empty, when reading and writing there is a pointer, you read one, the pointer moves back one, append a character to move back one, and so you again output is, the pointer will point to the empty place, so the output is emptyPrint(F.tell ())#output pointer position, byte, three bytes of a kanjif.close () output results:<class 'Str'>Earth<class 'Str'> 9

Related examples:

File Original content: Alexsel

f = open ("Name.txt","r+") Data= F.read (3)Print(Type (data), data)Print(F.tell ())#output current pointer positionF.write ("Earth Village")Print(F.tell ()) a= F.read ()Print(Type (a), a)Print(F.tell ()) f.close () output results:<class 'Str'>Ale313<class 'Str'>Xsel13

We can use Seek () to adjust the pointer position by reading the characters before our pointer.

f = open ("name.txt","w+", encoding="utf-8 " f.write (" sangumaolu "# This can move the pointer to the beginning (0), do not move, In the output is the empty data = f.read () f.close ()print(data) output result: Sangumaolu

When opening a file using append mode, the file pointer is directly at the end.

 f = open ( " asda.log  " ,  " a+  " , Encoding= " utf-8   " )  print  (F.tell ()) #   When using append, when opening the file, the pointer is directly in the last  data = F.read ()  print  (data) #   The pointer is directly at the end, so the output here is empty  f.seek (0) data  = F.read ()  print   7 alexsel  
Iii. Closing of documents

We used to use close () to close the file until we were in the file operation, and the file file was closed without causing an error.

Methods used in file operations

File is a document handle

File.close ()
Method refreshes any information that has not yet been written in the buffer and closes the file, which can no longer be written.

File.write ()
Writing data to a file

File.fulsh ()
Refresh file Internal buffers

F1 = open ("asda.log","r+", encoding="utf-8  ") f1.write (" ah ah ah ah ") F1.flush () f1.seek (0) Print (F1.read ()) Output result:
Ah ah ah ah ah

When the file is not closed, these things have not been saved to the hard drive, just in memory as you entered a string of characters in Notepad but not saved, just in memory, flush () function is to write the characters stored, as in Notepad, the memory of the contents of the flash to the hard disk.

File.name

Gets the file name of the action files

f = open ("name.txt","r+", encoding="utf-8 "  = f.nameprint(UT) output result: Name.txt

File.readable ()
Determine if open files are readable

F1 = open ("asda.log","r+", encoding="utf-8  ") pd=f1.readable ()print(PD) output: True

File.readline ()
Read only one row of data (automatically placing the pointer at the end of the first line, and then reading it, starting at the second line)

# Ask Price content: The first line is Sangumaolu, the second line is Alexself1 = open ("name.txt","r+" , encoding="utf-8"= f1.readline ()print  = f1.readline ()print(data1) f1.close () output: Sangumaolu Alexsel


File.seekable ()
Whether the pointer can be manipulated

F1 = open ("name.txt","r+", encoding="utf-8  "= f1.seekable ()print(UT) f1.close () Output: True
Summarize:
    • Whether you are reading a file or writing a file, you must call Close () to close the file after the operation is completed
    • But call with ... as to save Close ()
    • You can specify how to encode the read and write files by adding encoding= ' xxx ' to the function
    • We can use various methods to facilitate the operation of our files.
    • Read and write files we need to look at the position of the pointer.

Today's Python file operation is here, here is just a simple study, in the future when we do a simple project will deepen the practice.

Python learning: 7. File operation

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.