Python close the file open

open a file

1. Object create documents and programs on the disk is associated

2. Access to relevant documents by subject

File Operations

(1) read (2) writing (3) Other: adding, computing

Close the file

(1) cut off contact with the program file
(2) written to disk, and releases file buffers

open a file

. 1  the Open ()
 2 <variable> = Open (<name>, <MODE>) <name> A disk file name
 . 3 <MODE> Open Mode

Open mode

 

 

 

 

1 # For example, to open a named 7. The 1 .txt file
 2 textfile = Open ( " 7.1.txt " , ' R & lt ' )
 . 3  
. 4  # Open an audio file of a music.mp3
 . 5 binfile = Open ( ' music.mp3 ' , ' RB ' )

After use close the file using () method to close, release the license file format:

<Variable name> .close ()

Read and write files

read () Returns a string that contains the value of the contents of the entire file

the readline () Returns the value of the contents of the file string of the next line.

readlines () Returns the value of the entire contents of the file list, each newline to the end of his string.

 1 #1
 2 fname =  input("输入你要打开的文件:")
 3 fo = open(fname,'r')
 4 for line in fo.readlines():
 5 print(line)
 6 fo.close()
 7 #2
 8 with open ("demo1.txt",'r',encoding='utf8')as f:
 9 for line in f.readlines():
10 print(line,end='') 

 

The code applies only to short code, the disadvantage is: when the file is very large, one-time to read the contents of the list will take up a lot of memory,

Rigid enforcement of speed. Reasonable approach is progressive read into memory, and progressive process. Python file itself as a sequence of rows,

All lines traverse the document.

. 1 . 1 fname = INPUT ( " Enter your file to be opened: " )
 2 2 FO = Open (fname, ' R & lt ' )
 . 3 . 3 for Line in FO ():
 . 4 . 4 Print (Line)
 . 5 . 5 fo.close ()

Write to file

Write data to a file from the computer memory
write (): This article contains a string or binary data blocks written to the file.
writelines (): For a list of actions to receive a list of strings as arguments, it
had written to the file.

1  # writing a 
2 fname = INPUT ( " Enter file to write: " )
 . 3 FO = Open (fname, ' W + ' )
 . 4 LST = [ ' This IS A Demo ' , ' and Demo ' ]
 . 5  FO. the writelines (LST)
 . 6  for Line in FO:
 . 7  Print (Line)
 . 8  fo.close ()
 . 9  
10  # writing two 
. 11 LST = [ ' This Demo IS A ' , ' and Demo']
12 with open ("demo1.txt",'a',encoding='utf8')as f:
13     for x in lst:
14         f.write('{}\n'.format(x))
15         
16 with open ("demo1.txt",'r',encoding='utf8')as f:
17     for line in f.readlines():
18         print(line,end='')    

Results of the:

 

Guess you like

Origin www.cnblogs.com/yangbiao6/p/11789648.html