ArticleDirectory
- 1. Open
- 2. Read files
- 3. Write files
In python, file operations can be implemented through open functions, which is indeed similar to fopen in C. Obtain a file object through the open function, and then call the read (), write () and other methods to read and write the object.
1. Open
After opening a file using open, remember to call the close () method of the file object. For example, you can use the try/finally statement to ensure that the file can be closed at last. File_object=Open ('Thefile.txt')
Try:
All_the_text=File_object.read ()
Finally:
File_object.close ()
Note: The open statement cannot be placed in the try block, because when an exception occurs when the file is opened, the file object file_object cannot execute the close () method.
2. Read a text file Input = Open ( ' Data ' , ' R ' )
# The second parameter is R by default.
Input = Open ( ' Data ' )
Read Binary files Input=Open ('Data','RB')
Read all content File_object=Open ('Thefile.txt')
Try:
All_the_text=File_object.read ()
Finally:
File_object.close ()
Read fixed bytes File_object = Open ( ' Abinfile ' , ' RB ' )
Try :
While True:
Chunk = File_object.read ( 100 )
If Not Chunk:
Break
Do_something_with (chunk)
Finally :
File_object.close ()
Read each line List_of_all_the_lines=File_object.readlines ()
If the file is a text file, you can directly traverse the file object to get each line: ForLineInFile_object:
Process Line
3. Write a file to write a text file
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> output = open ( ' data ' , ' W ' )
write binary files
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> output = open ( ' data ' , ' WB ' )
append a file
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> output = open ( ' data ' , ' W + ' )
Write Data File_object=Open ('Thefile.txt','W')
File_object.write (all_the_text)
File_object.close ()
Write multiple rows File_object.writelines (list_of_text_strings)
Note that calling writelines to write multiple rows has a higher performance than using write for one-time writing.
Python daily delicious series (total)
Python daily delicious (15)-Python Regular Expression operation guide (used by Re) (for conversion)
Python daily delicious (16)-string filtering techniques, MAP and itertools. imap
Python every day (17)-open read/write files
Python every day delicious (18)-linecache. Getline () read a specific row in the file
Python daily delicious (19)-time processing datetime
...