Basic knowledge of Python project 4 documents

  • 2020-05-27 06:02:20
  • OfStack

Having covered the basics of functions, statements, and strings, this article focuses on the basics of files (very similar to other languages).

1. Basic operation of files

A file is a collection of data stored on external media (such as disk). The operation process of the file is as follows:

Open file (read/write)- > Read and write file (read\readline\readlines\write\writelines)- > Close the file

1. Open the file

Call the function open to open the file, and its function format is:

file_obj=open(filename[, mode[, buffering]]) returns 1 file object (file object)

-- filename file name (only 1 mandatory parameter)

· original string r'c:\temp\ test.txt '

· transfer string 'c:\\temp\\ test.txt '

-- mode file mode

· r reading mode

· w write mode

· a append mode (written after last time)

· + read/write mode (no file is created and can be added to other modes for use)

· b base 2 mode (can be added to other modes)

-- buffering buffer (optional parameter)

· parameter =0 or False input/output I/O is unbuffered and all read/write operations are for hard disk

· parameter =1 or True input/output I/O is buffered, memory instead of hard disk

・ parameters > The number 1 represents the size of the buffer, in bytes.-1 or negative represents the use of the default buffer size

Note: when processing binary files such as sound clips or images using 'b' binary mode, 'rb' can read 1 binary file.

Close the file

close method is used to close the file should be borne in mind, because Python might cache (somewhere) to temporarily store data for the sake of efficiency, write data, if the program collapse suddenly, data is written to the file, not to be on the safe side, in the use after the file is closed. If you want to ensure that the file is closed, you should use try/finally statements, and call close method in finally clause. Such as:


 #Open your file
  try:
    #Write data to your file
  finally:
   file.close()

3. Read and write files

The function write method is called to write data to the file. The function format is:

The file_obj.write (string) parameter string is appended to the saved part of the file

file_obj.writelines (sequence_of_strings) passes only one parameter, list [] tuple () dictionary {}

Note: the order in which the strings appear in a useful dictionary is random.


# use write() Write files  
file_obj=open('test.txt','w') 
str1='hello\n' 
str2='world\n' 
str3='python' 
file_obj.write(str1) 
file_obj.write(str2) 
file_obj.write(str3) 
file_obj.close() 
# use writelines() Write files  
file_obj=open('test.txt','w') 
str1='hello\n' 
str2='world\n' 
str3='python' 
file_obj.writelines([str1,str2,str3]) 
file_obj.close() 
# The output   local test.txt file  
hello 
word 
python 

The function read method is called to read the data. The function format is :var= file_obj.read (), where read is read in full and string is returned; readline reads 1 line and returns string; readlines reads all the lines of the file and returns a list of string. Example:


# use read 
print 'Use the read' 
file_obj=open('test.txt','r') 
s=file_obj.read() 
print s 
file_obj.close 
# use readline 
print 'Use the readline' 
file_obj=open('test.txt','r') 
line1=file_obj.readline() 
line1=line1.rstrip('\n') 
print 'l1 ',line1 
line2=file_obj.readline() 
line2=line2.rstrip('\n') 
print 'l2 ',line2 
line3=file_obj.readline() 
line3=line3.rstrip('\n') 
print 'l3 ',line3 
file_obj.close 
# use readlines 
print 'Use the readlines' 
file_obj=open('test.txt','r') 
li=file_obj.readlines() 
print li 
file_obj.close 

The output content is as follows:


Use the read 
hello 
world 
python 
Use the readline 
l1 hello 
l2 world 
l3 python 
Use the readlines 
['hello\n', 'world\n', 'python'] 

It can be found that when using the readline() function, the result it returns is 'hello\n' string, so rstrip should be used to remove '\n'; otherwise, print output will have a total blank of 1 line.


# Formatted write  
fd=open('format.txt','w') 
head="%-8s%-10s%-10s\n"%('Id','Name','Record') 
fd.write(head) 
item1="%-8d%-10s%-10.2f\n"%(10001,'Eastmount',78.9) 
fd.write(item1) 
item2="%-8d%-10s%-10.2f\n"%(10002,'CSDN',89.1234) 
fd.write(item2) 
fd.close() 
# The output  
Id  Name  Record  
10001 Eastmount 78.90  
10002 CSDN  89.12 

2. Files and loops

The basic operation and use method of files have been introduced previously, but file operation is usually associated with loop. The while loop and for loop are described below to realize file operation. The code is as follows:


# use while cycle  
fr=open('test.txt','r') 
str=fr.readline() 
str=str.rstrip('\n') 
while str!="": 
 print str 
 str=fr.readline() 
 str=str.rstrip('\n') 
else: 
 print 'End While' 
fr.close 
# use for cycle  
rfile=open('test.txt','r') 
for s in rfile: 
 s=s.rstrip('\n') 
 print s 
print 'End for' 
rfile.close() 

Among them, for calls the iterator iterator, which provides a method to access each element of an aggregate object in sequence, which is equivalent to getting the iterator of the object through the Iter function, and then getting the next value through the next function (which does not need any parameters when the method is called).for can traverse iterator_obj including List\String\Tuple\Dict\File.


 s='www.csdn.NET'
  si=iter(s)   # Generating iterator 
  print si.next() # call next Get elements in turn , Raised when the last iterator does not return a value StopIteration abnormal 

3. Summary

This article mainly describes the basic knowledge of Python files, including opening, reading and writing files, closing files, using a loop to read and write files, and iterator knowledge.


Related articles: