[Programmer technical skills] Learning a scripting language python (1) file processing,
Currently, the main language used in my work is java. java can play a good role in enterprise-level applications. However, sometimes I need to perform minor tasks, such as batch file update and webpage capturing, at this time, it seems too cumbersome to use java. So I learned the python script language.
This article mainly describes how to process text files in python and some basic knowledge about python.
Okay, let's get started ......
Requirement Description
- Process text files: Read a local file and process it row by row
Speaking of File Processing, I have to say that python's built-in function open
Open(File,Mode = 'R',Buffering =-1,Encoding = None,Errors = None,Newline = None,Closefd = True,Opener = None)
Function Definition: open a file and return the corresponding Object. If the specified file cannot be openedOSErrorWill throw
Where,file
Parameter indicates the name of the file to be opened,
mode
Is the open mode,
BufferingUsed to control file buffering. The default value is0
, Indicating no buffering, set1
There will be a buffer,
EncodingIs file encoding. The default value is system encoding,
ErrorsIt is an optional parameter used to specify how to handle errors during file encoding and decoding. Note that this error will not be handled in the binary mode ('B ') medium,
Newline It is used to control the working mode of common line breaks (only working in text mode)
mode
The following modes can be used:
Character |
Meaning |
'R' |
Open (default) in read-only mode) |
'W' |
Open in write mode. The file content will be deleted first. |
'X' |
If the file already exists, open it exclusively |
'A' |
Open in write mode. When the file exists, the content will be added at the end of the content |
'B' |
Binary |
'T' |
Text mode (default) |
'+' |
Update a disk file (reading and writing) |
'U' |
Universal newlinesMode (obsolete) |
Generallyopen()
You can retrieve the file content by calling the file name parameter without adding any other parameters. The default mode is read mode. If you want to read a special file (such as a video or image file), you must use 'B' mode.
The following is an example of Text processing:
1 # encoding=utf-8 2 file_path = "d:/test.txt" 3 file = open(file_path) 4 5 #####1. read()##### 6 7 print(file.read()) 8 9 #####2. readline()#####10 11 line = file.readline()12 while line:13 print(line)14 line = file.readline()15 16 #####2. readlines()#####17 18 for line in file.readlines():19 print(line)
20 file.close()
The preceding three methods are used to read files:Read (), readline (), readlines ()
- Readlines:The most common method is to convert each row of a file into a list, and then perform various operations.
- Read: All content of the file is returned at a time.
- Readline: Returns the content of a row of the file. The next call will continue to read the next row until the read is complete.
OK. This is the example for processing files!