Python Tour: File handling

Source: Internet
Author: User
Tags file handling

Introduction to a document operation and theory

Computer system is divided into: hardware, operating system, application of three parts
We use Python or other programs, want to keep the data permanently, we have to write to the hard disk, but the application is no way to directly manipulate the hardware, which is used in the operating system.
The operating system to the complex hardware operation into a simple interface to the user, wherein the file is the operating system provided to the application to operate the virtual concept of the hard disk, the user program through the system operation files, you can report data saved to the hard disk

With the concept of a file, we no longer have to consider the details of the operation of the hard disk, just the process of manipulating the files:

# 1. Open the file, get the file handle and assign the value to a variable #2. Manipulating files by handle #3. Close File
Two how to manipulate files in Python
# 1. Open the file, get the file handle and assign a value to a variable f=open ('a.txt','r', encoding='utf-8'# default open mode for RT R Read-only T text T can not write, default open text # 2. Manipulating files with a handle data=f.read ()#3. Close file f.close ()
three f=open (' A.txt ', ' r ') process analysis
# 1. The application initiates a system call to the operating system open (...) # 2. The operating system opens the file and returns a file handle to the application # 3. The application assigns the file handle to the variable F
four emphasis!!!

#emphasize the 1th:Open a file containing two parts of the resource: the operating system-level Open file +the variable for the application. When you have completed a file, you must recycle the two parts of the file with a non-landed method:1, F.close ()#Recycle open files at the operating system level2.delF#Recycle application-level variableswhere del F must occur after f.close (), otherwise it will cause the operating system open files are not closed, the use of resources, and Python automatic garbage collection mechanism determines that we do not have to consider Del F, which requires us, after the operation of the file, Be sure to remember F.close () although I say so, but a lot of students will not forget the face of F.close (), for these not long-brain students, we recommend a fool-like operation: Using the WITH keyword to help us manage the context with open ('a.txt','W') as F:PassWith Open ('a.txt','R') as Read_f,open ('B.txt','W') as Write_f:data=Read_f.read () write_f.write (data)

# Emphasis 2nd:F=open (...) is opened by the operating system file, then if we do not specify the encoding for open, then the default encoding of the opening file is obviously the operating system, the operating system will use its own default encoding to open the file, under Windows is GBK, under Linux is Utf-8. This is the use of the last lesson of the character encoding knowledge: to ensure that no garbled, the file in what way, it will be opened in what way. F=open ('a.txt','r', encoding='utf-8  ')

File and open in the five Python2

# first, there is only one option to manipulate files in Python3, which is open () # There are two ways of Python2: file () and open ()  is file

Three ways to manipulate files

Let's take a look at the function open (), to use the file in any way ———— even if you just print its contents, you have to open the file before you can access him.

The keyword with is closed after you no longer need to access the file.

You also call Open () and close () to turn the file on and off, but when you do so, if the program has a bug that causes the close () statement to not be executed, the file will not be closed (because the program opens the file when the notification system is open, so the system should be notified when it is closed, the file program does not tell There is a limit to the number of open files when the system determines that the file has not been called and then closes it through a certain period of time. The program does not need to access the file should notify the system to close the file, reduce the consumption of two of resources, although it will pull garbage automatically recycled). It may seem trivial to you, but improper closing of files may result in loss or loss of data. If Close () is called prematurely, you will notice that the file is closed, which results in more errors. But with the Pytho, you can make sure that you just open the file and use it when you need it, and Python will automatically turn it off when you want.

#MasterF.read ()#Read all content, cursor moves to end of fileF.readline ()#reads a line of content and moves the cursor to the beginning of the secondF.readlines ()#reads the contents of each line and stores it in the listF.write ('1111\n222\n')#Write to text mode, you need to write line breakF.write ('1111\n222\n'. Encode ('Utf-8'))#Write line break for B modeF.writelines (['333\n','444\n'])#file ModeF.writelines ([Bytes ('333\n', encoding='Utf-8'),'444\n'. Encode ('Utf-8')])#b Mode#UnderstandF.readable ()#whether the file is readableF.writable ()#whether the file is readableF.closed#whether the file is closedF.encoding#if the file open mode is B, the attribute is notF.flush ()#immediately swipe the contents of the file from the memory to the hard diskF.name

One read file1. Read the entire file-read ()

Let's take a look at the function open (), to use the file in any way ———— even if you just print its contents, you have to open the file before you can access him.

The keyword with is closed after you no longer need to access the file.

You also jump to open and close the file using open () and close (), but when doing so, if the program has a bug that causes the close () statement to not be executed, the file will not be closed (because the program opens the file when the notification system is open, so the system should be notified when it is closed, the file program does not tell the There is a limit to the number of open files when the system determines that the file has not been called and then closes it through a certain period of time. The program does not need to access the file should notify the system to close the file, reduce the consumption of two of resources, although it will pull garbage automatically recycled). It may seem trivial to you, but improper closing of files may result in loss or loss of data. If Close () is called prematurely, you will notice that the file is closed, which results in more errors. But with the Pytho, you can make sure that you just open the file and use it when you need it, and Python will automatically turn it off when you want.

A.txt content is as follows: Hungry Hungry hungry hungry hungry hungry 1 hungry hungry hungry hungry 2 hungry hungry hungry starve hungry hungry 3
With open ('a.txt', mode='r', encoding='utf-8  ') as F:    Print(F.read ())
Results:
Hungry, hungry, hungry, hungry, hungry, hungry. 1
Hungry, hungry, hungry, hungry, hungry, hungry. 2
Hungry, hungry, hungry, hungry.
2, Progressive read readline ()
 1, implemented through a for loop 
with open ( a.txt " Span style= "color: #800000;" > ' , Mode= " rt ' , Encoding= " utf-8 ' ' as F: #以上说过默认rt, R read-only, T-text for Line in f: print results as follows: Hungry, hungry, hungry, hungry, hungry, starving, starving, hungry, hungry, starving, hungry, starving. 2 Hungry, hungry, hungry, hungry, starving. 3
#因为print () self-wrapping, If you don't want it to be wrapped, you can print (line,end= ')

2, through the ReadLine () function f.readline () # reads a line of content, and the cursor moves to the beginning of the second
Open (' a.txt ',mode=' RT ',encoding= asF:
Print (F.readline ())
Print (F.readline ())
Print (F.readline ())
3. Create a list containing the contents of each line of the file ReadLines ()

When using the keyword with, the file object returned by open () is used only within the with code block. If you want to use it outside of a with code block, you can store the rows of the file in a list in a with code block and use the list outside of the with code block: You can work with parts of the file immediately, or you can defer processing after the program.

#文件过大时, this method is not recommended because it is read into memory, and you do not want the memory overflow to crash!
With open ('a.txt', mode='R', encoding='Utf-8') as F:lines=F.readlines ()Print(lines) #这是故意打印出来让大家看的 forLineinchlines:Print(Line.rstrip ()) #rstrip () deletes the specified character at the end of a string (the default is a space)
The results are as follows:
[' Hungry, hungry, hungry, hungry, hungry 1\n ', ' hungry, hungry, hungry, hungry, hungry 2\n ', ' hungry, hungry, hungry, hungry 3\n '] #这是lines的结果
Hungry, hungry, hungry, hungry, hungry, hungry, 1 #这是line的结果

Hungry, hungry, hungry, hungry, hungry, hungry. 2

Hungry, hungry, hungry, hungry.

Two write files. Write

One of the simplest ways to save data is to write it to a file.

1. Write to empty file

To write text to a file, you need to provide another argument when calling open (), telling Python that you want to write to the open file.

In other words, Note: # 1, when the file exists, empty # 2, when the file does not exist, create an empty document #3, that is, regardless of how to raise the equivalent of creating an empty file and then writing the content

With open ('a.txt', mode='w', encoding='utf-8  ') as F:    f.write ('I love Python')
The results are as follows:
I Love Python #这是现在a. txt file content that he would have otherwise content, see above

2. Attaching to a file

You want to add content to the file instead of overwriting the original content, and you can open the file in attached mode.

When you open a file in attach mode, Python does not empty the file before returning the file object, and the contents of the file you write are appended to the end.

If the specified file does not exist, an empty file is created.

With open ('a.txt', mode='a', encoding='utf-8  ') as F:    f.write ('\ni love money\n')    F.write ("I Love music\n")
The results are as follows:
I Love Python   #a. txt content that exists
I Love Money
I Love Music
3. Inserting multiple strings at the same time. Writelines
With open ('a.txt', mode='a', encoding='utf-8  ') as F:    f.writelines (['qeqwe\n','  qweadqe\n'])

The results are as follows:
I Love Python
I Love Money
I Love Music
Qeqwe #追加的
QWEADQE #追加的

  

Python Tour: File handling

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.