This article covers Python open/create file objects, read and write files, move file pointer positions, get command line arguments.
1. Open ()
The open function returns a file object in the specified mode, such as: File_object = open (filename,access_mode= ' R ', Buffering=-1), which is opened by default in R mode.
FileName: Indicates the file name (string) to open, either an absolute path or a relative path
Access_mode: File open Mode (string), commonly used patterns have ' r ', ' W ', ' A ', not very common and ' u ' and ' B '
' R ' mode: Open in read mode, cannot write operation, file must be existing
' r+ ' mode: Open as read-write, file must be existing
' W ' mode: Open in write mode, cannot read operation, if file exists, then empty first, then re-create, if not present, create file
' w+ ' mode: Open as read-write, if the file exists, then empty first, then re-create, if not, create the file
' A ' mode: Open in Append mode, cannot read operation, append data to the end of file, if not present, create file
' A + ' mode: Opens as read-write, appends data to the end of the file, or creates a file if it does not exist
' B ' mode: Open in binary mode, can not appear as the first character, need to be used in combination with the above pattern, such as ' RB ', ' rb+ ', etc.
' u ' mode: indicates universal line feed support, the file must already exist
Buffering: means that the Access file is buffered, 0 means no buffering, 1 is buffering a row of data, the other value greater than 1 means using the given value as the buffer size, negative means using the system default buffering mechanism, default is-1, the system default mode is generally used.
2. File ()
File is a class, file () creates a file object in the specified pattern, with the same functionality as open () and can be replaced arbitrarily. Typically open is used to create a file object, using Isinstance (obj,file) to determine if obj is a document object.
3.read (), ReadLine (), ReadLines ()
Read (): reads a specified number of bytes into a string, negative numbers are read to the end of the file, by default-1
| 123456789101112131415161718 |
>>> file_obj = open(‘test.txt‘,‘r‘)>>> file_obj.read()‘dfdff\n‘>>> file_obj.seek(0)>>> file_obj.read(0)‘‘>>> file_obj.read(1)‘d‘>>> file_obj.read(2)‘fd‘>>> file_obj.read(-1)‘ff\n‘>>> file_obj.seek(0)>>> file_obj.read(1000)‘dfdff\n‘>>> file_obj.seek(0)>>> file_obj.read(-5)‘dfdff\n‘ |
ReadLine (): Reads a line of the file, including the line terminator, you can set the value of the size parameter, which by default is-1
| 1234567 |
>>> file_obj =open(‘test.txt‘,‘r‘)>>> file_obj.readline()‘dfdff\n‘>>> file_obj.readline(2)‘al‘>>> file_obj.readline(-1)‘exzhou\n‘ |
ReadLines (): reads all remaining rows and returns as a list of strings
| 123 |
>>> file_obj.seek(0)>>> file_obj.readlines()[‘dfdff\n‘, ‘alexzhou\n‘, ‘zhoujianghai\n‘] |
4. Write (), Writelines ()
PS: Both methods do not automatically add line terminator, you need to write data before you add
| 123456789101112131415161718192021 |
>>> file_obj = open(‘test.txt‘,‘w+‘)>>> file_obj.write(‘alexzhou‘)>>> file_obj.write(‘ python‘)>>> file_obj.seek(0)>>> file_obj.readline()‘alexzhou python‘>>> l = [‘my‘,‘name‘,‘is‘,‘zhoujianghai‘]>>> l = ‘ ‘.join(l)>>> file_obj.writelines(l)>>> file_obj.seek(0)>>> file_obj.readline()‘alexzhou pythonmy name is zhoujianghai‘ >>> file_obj.write(‘hello \n‘)>>> file_obj.write(‘world \n‘)>>> file_obj.seek(0)>>> file_obj.readline()‘alexzhou pythonmy name is zhoujianghaihello \n‘>>> file_obj.readline()‘world \n‘ |
5. Seek (), tell ()
Seek (): Moves the file pointer to a different location and can specify the offset and start position. Starting at position 0 means starting with the file header, 1 means starting at the current position, 2 means starting at the end of the file, and 0 by default.
Tell (): Indicates the position of the current file pointer in the file, starting with the file header.
| 12345678910111213141516 |
>>> file_obj.seek(0)>>> file_obj.tell()0>>> file_obj.seek(5)>>> file_obj.tell()5>>> file_obj.seek(5,1)>>> file_obj.tell()10>>> file_obj.seek(5,2)>>> file_obj.tell()57>>> file_obj.seek(5,0)>>> file_obj.tell()5 |
6. File iterations and closing files
You can use a for loop to read a file one line at a
| 12345678910 |
>>> file_obj = open(‘test.txt‘,‘w+‘)>>> file_obj.write(‘hello \n‘)>>> file_obj.write(‘world \n‘)>>> file_obj.seek(0)>>> for eachline in file_obj:... print eachline,... hello world>>> file_obj.close() |
Ps:print is followed by a semicolon: avoid the print statement by default adding a newline symbol to the printed content.
7. Common Properties of OS modules
Because the line separators and file separators are different for each operating system, you can use the following properties of the OS module to avoid encountering these problems when porting code.
Os.linesep Line delimiter string
Os.sep file delimiter string
Os.pathsep Path delimiter string
Os.curdir Current directory string
Os.pardir Parent Directory String
Look at the print results below
| 1234567891011 |
>>> importos>>> os.sep‘/‘>>> os.linesep‘\n‘>>> os.pathsep‘:‘>>> os.curdir‘.‘>>> os.pardir‘..‘ |
8. Get command-line arguments
Create the argv.py file and enter the following code
| 1234 |
importsys commands = sys.argvprintcommands |
Execution: Pyton argv.py 123, printing results:
[' argv.py ', ' 123 ']
Source: http://codingnow.cn/language/372.html
From for notes (Wiz)
python-file Operations (1)