This is also the content of the basic Python tutorial (version 2). It is more interesting and practical than the previous one, change "Basic" to "advanced ".
Python e-book sharing address:Http://yunpan.cn/Q2U87uGrNiTA3
This section describes file operations.
-------------------------------
Open a file
OpenThe function is used to open a file. The syntax is as follows:
Open (name [, mode [, buffering])
OpenThe function uses a file name as a unique mandatory parameter and returns a file object. Suppose I want to open my hard disk (I:/Python/test.txt) File, you can use the following method:
>>> F = open (R'I: \ Python \ test.txt')
OpenCommon Values of Pattern Parameters in Functions
Basic file Method
Opening a file is the first step. You need to read or write the file below.WriteAndReadMethod.
# Write File Content >>> F = open (' Test.txt ' , ' W ' ) >>> F. Write ( ' Hello, ' ) >>> F. Write ( ' World! ' ) >>> F. Close () # Read File Content >>> F = open ( ' Test.txt ' , ' R ' ) >>> F. Read (4) # Read the first 4 characters ' Hell ' >>> F. Read () # Read all remaining characters ' O, world! '
Close file
Remember to useCloseMethod to close the file. Although a file object is exitingProgramIt will be automatically closed, but it does not harm to close the file. You can avoid unnecessary modifications in some operating systems or settings, this will also avoid using the quota of opening files in the system.
How to use basic files
For example, test.txtThe file contains the following content:
-----------------------------
Welcome to this file
There is nothing here except T
This stupid haiku
-----------------------------
The following describes how to read an object:
# Read (n) specified parameter >>> F = open (R ' I: \ Python \ test.txt ' ) >>> F. Read (7 ) ' Welcome ' >>> F. Read (4 ) ' To ' >>> F. Close () # Read () does not specify parameters >>> F = open (R ' I: \ Python \ test.txt ' ) >>> Print F. Read () Welcome to this filethere Is Nothing here Except This stupid haiku >>> F. Close () # Readline () >>> F = open (R ' I: \ Python \ test.txt ' ) >>> For I In Range (3 ): Print STR (I) + ' : ' + F. Readline () 0: Welcome to this file 1: There Is Nothing here Except 2 : This stupid haiku >>> F. Close () # Readlines () >>> Import Pprint >>> Pprint. pprint (open (R ' I: \ Python \ test.txt ' ). Readlines ())[ ' Welcome to this file \ n ' , ' There is nothing here before t \ n ' , ' This stupid haiku ' ]
ReadlineReturns the string of a row., ReadlinesReturns the string list containing all the content of the file.,Each element is a string of one line..
PprintModulePprintThe content is displayed in a single line of each small item.
The following describes how to write a file:
>>> F = open (R'I: \ Python \ test.txt','W')#The default value is to read files. You do not need to add 'R'. You must add 'w' to write files'>>> F. Write ('This \ nis no \ nhaiku')>>> F. Close ()
>>> F = open (R'I: \ Python \ test.txt')>>> Lines =F. readlines ()>>> Lines [1] ="Isn' t a \ n">>> F = open (R'I: \ Python \ test.txt','W')>>>F. writelines (lines)>>> F. Close ()
Iterate the File Content
1. byte processing
The most common method to iterate the file content isWhileUse in LoopReadMethod. For example, you can use the following method to loop every character:
F =Open (filename) Char= F. Read (1)WhileCHAR: Process (char) Char= F. Read (1) F. Close ()
ReadThe string returned by the method will contain one character until the end of the file,ReadReturns an empty string,CharWill become false.
As you can see, char = f. Read (1) is repeatedly used,CodeRepeated pass is considered a bad thing. Let's look at the following method:
F =Open (filename)WhileTrue: Char= F. Read (1)If NotCHAR:BreakProcess (char) F. Close ()
HereBreakThe statement is frequently used (which makes the code more difficult). However, it is better than the previous method.
2. Read all content
If the file is not large, you can useReadMethod to read the entire file at a time, or useReadlinesMethod.
#Use read to iterate each characterF =Open (filename)ForCharInF. Read (): Process (char) F. Close ()
#Use readlines to iterate rows:F =Open (filename)ForLineInF. readlines (): Process (line) F. Close ()
3. UseFileinputFor Iteration
FileinputThe module contains a function to open a file. You only need to pass a file name to it.
ImportFileinputForLineInFileinput. Input (filename): Process (line)
4. File iterator
Okay! This isPython2.2Then there is a method. If it is available at the beginning, the above method may not exist. File objects can be iterated, which means they can be directly stored inForIterate on them in a loop
F =Open (filename)ForLineInF: Process (line) F. Close ()
Let's take a look at the following example:
>>> F = open (R ' I: \ Python \ test.txt ' , ' W ' ) >>> F. Write ( ' First line \ n ' ) >>> F. Write ( ' Second line \ n ' ) >>> F. Write ( ' Third line \ n ' ) >>> F. Close () >>> Lines = List (open (R ' I: \ Python \ test.txt ' )) >>> Lines [ ' First line \ n ' , ' Second line \ n ' , ' Third line \ n ' ] >>> First, second, third = open (R ' I: \ Python \ test.txt ' ) >>> First ' First line \ n ' >>> Second ' Second line \ n ' >>> Third ' Third line \ n '
In this example:
- Sequence is used to unpack an opened file and put each line into a single variant. This is very useful because it generally does not know how many rows are in the file, but it demonstrates the "iteration" of the file ".
- After writing a file, you must close the file to ensure that the data is updated to the hard disk.