This blog will cover Python's file processing and related input and output, which will involve file objects (its built-in functions, built-in methods and properties), standard file and file system access methods, and file execution. (Welcome everyone to my new blog to take a walk)
File Object
The file object can be used not only to access normal disk files, but also to access "files" on any other type of abstraction. The built-in function open () returns a file object that is used for subsequent related operations of the file.
File built-in functions (open () and files ())
As a key, the built-in function open () and file () provide a common interface for initializing input/output (I/O) operations. The open () function returns a file file object when the file is successfully opened, and throws a IOError exception if unsuccessful. The syntax for the open () function is as follows:
file_object = open(file_name, access_mode="r", buffering=-1)
file_name is the file name of the file that will be opened, either a relative path or an absolute path. Access_mode is also a string that represents the open file mode, with "R" (for Read), "W" (For Write), "a" (for append). with "R" The file opened by the schema must be present. Open the file in "W" mode, if the file does not exist, it will be created, if the file already exists, then the file is emptied to write data. " A "mode is similar to" w ", the only difference is that" a "is adding data at the end of the file and does not empty the original data of the file. If the file does not exist, create it. Access_mode defaults to" R ". The buffering is used to indicate the buffering method used to access the file. Where 0 means no buffering, 1 means that only one row of data is buffered, and any other numeric value greater than 1 represents the buffer size using the given value. This parameter is not provided or a negative value is used to represent the system default buffering mechanism. See in more detail:
File built-in methods
After open () executes successfully and returns a file object, all subsequent operations on the file are carried out through this handle. There are 4 types of file methods: input, output, move within the file, and iterate.
Input
The read () method is used to read bytes directly into a string, reading a given number of bytes at most. The size parameter is not given (default is-1) or the size value is negative, and the file is read until the end.
The ReadLine () method reads a line of the file, and then the entire line (including the line terminator) is returned as a string. Similar to the Read () method, it also has an optional size parameter, which defaults to-1, which represents the end of the read line. If the parameter is provided, such as 5, it will read only 5 characters of that line
The ReadLines () method does not return a string like the other two methods. He would read all the lines (remaining) and then return them as a list of strings. Its optional parameter sizhint represents the maximum byte size returned. If it is greater than 0, Then all the rows returned should have sizeint bytes.
Output
Wirte () The function of the built-in method is the opposite of Read () and ReadLine (). It writes a string containing text data or binary data blocks to a file.
As with ReadLines (), the Writelines () method is a list-based operation that takes a list of strings as parameters and writes them to the file. But the line terminator does not automatically join, and if necessary, you must call the Writelines () money at the end of each line with a line terminator .
Moving within files
The Seek () method (similar to the fseek () function in C) can move the file pointer to a different location in the file. The offset byte represents the relative offset to a position. The default value for the position is 0, which means that from the beginning of the file (that is, the absolute offset), 1 represents the current position, 2 delegates are counted from the end of the file.
The Tell () method complements the Seek () method, which tells you where the current file pointer is located in the file – in bytes from the beginning of the file.
File iterations
File iterations are so easy for programmers to access files:
f = open("test.txt""r")forin f: print eachLine
Other
Close () ends the access to it by closing the file.
The Fileno () method returns a descriptor for the open file. This is an integer
Calling the flush () method directly writes the data in the internal buffer to the file immediately, rather than passively waiting for the output buffer to be written.
It's time for a vote.
The above pull so much, or hands-on practice intuitive, to write some demo
>>> f = open ("Test","R") >>> Fileno (f) Traceback (most recent): File"<stdin>", line1,inch<module>nameerror:name' Fileno 'is not defined>>> F.fileno ()3>>> F.tell ()0>>> forEachlineinchF:...Print Eachline,...This file just forTest.line1Line2@line3!line4*end!!! >>> F.tell () $>>> F.seek (0,0) >>> F.tell ()0>>>
>>> f = open("newfile""w")>>> f.write("This is a test")>>> f.tell()14>>> f.writelines(["line1""line2""line3"])>>> f.close()>>> f = open("newfile""r"forin f:... print eachLine,...
File built-in properties
File objects In addition to methods, there are some data properties. These properties hold additional data related to the file object.
properties of the file object |
Description |
File.closed |
Represents a file to close |
File.encodeing |
The encoding used by the file |
File.mode |
Access mode when the file is opened |
File.name |
Filename |
File.newline |
To read to the line terminator is none, only one line terminator is a string, and when the file has multiple line separators, it is a list that contains all the currently encountered line Terminators |
Standard file
Standard files have these 3: standard input, standard output, standard error
A handle to these files can be accessed through the SYS module in Python. Sys.stdin, sys.stdout, sys.error represent standard input, standard output, standard error, respectively. In general, the print statement is output to Sys.stdout, raw_ Input () is received from Sys.stdin.
Command-line arguments
I believe that the students familiar with C language are familiar with command line parameters, in C language, argc and argv respectively represent the number of parameters and parameter vectors. The argv variable represents an array of strings that consist of each parameter entered from a command line, and the ARGC variable represents the number of arguments entered. In Python, The ARGC is not there. The SYS.ARGV in Pyhton is quite the argv of C, and Len (SYS.ARGV) is the equivalent of ARGC in C. In short:
-SYS.ARGV is a list of command line arguments
-Len (SYS.ARGV) is the number of command line arguments
Look at a small example:
##argvTest.pyimport sysprint"you entered""arguments..."print"they were: ", str(sys.argv)
likai@likai:~/python$ 4344.445were: [‘argvTest.py‘‘43‘‘test‘‘44.44‘‘haha‘]
File system
Access to file systems is mostly implemented through Python's OS modules. This module is the primary interface for Python to access the operating system functionality. The OS module is actually just the front end of the module that is actually loaded, and the specific implementation relies on the specific operating system.
The OS module can manage the process and process runtime environment, and the OS module is responsible for most of the file system operations. Of course, this blog is mainly about OS file system operation. These actions include deleting/renaming files, traversing the directory tree, and managing file permissions.
Another module, Os.path, can do some action on the pathname. It provides functions such as managing and manipulating various parts of the file path name, obtaining file or subdirectory information, file path queries, and so on.
File/directory Access functions for OS modules
function |
Description |
File processing |
|
Mkfifo ()/mknod () |
Create a named pipe/create a file node |
Remove ()/unlink () |
deleting files |
Rename ()/renames () |
Renaming files |
Stat () |
Return file information |
Sysmlink () |
Creating Symbolic Links |
Utime () |
Update Time stamp |
Tmpfile () |
Create disease open (' w+b ') a new temporary file |
Walk () |
Generate all file names under a directory tree |
Directory/Folder |
|
ChDir () |
Change the current working directory |
Chroot () |
Change the root directory of the current process |
GETCWD () |
Return to current working directory |
mkdir ()/mkdirs () |
Create a directory/multi-level catalog |
RmDir ()/rmdirs () |
Delete directory/multi-level directory |
Access/Permissions |
|
Access () |
Verify Permissions |
chmod () |
Change permissions |
Chown () |
Change owner |
Umask () |
Set default Permissions |
File descriptor Operations |
|
Open () |
The underlying operating system open |
Read ()/write () |
Read/write Data |
DUP ()/DUP32 () |
Copy file descriptor/function same, but copy to another file descriptor |
Device number |
|
Makedev () |
Create an original device number from the major and minor device numbers |
Major ()/minor () |
Get the Major/minor device number from the original device number |
Path name access functions in the Os.path module
function |
Description |
Separated |
|
BaseName () |
Remove directory path, return file name |
DirName () |
Remove file name, return directory path |
Join () |
Make separate parts a path name |
Split () |
Returns (DirName (), basename ()) tuples |
Splitdrive () |
Return (dirvename, pathname) tuples |
Splitext () |
Return (filenameextension) tuples |
Information |
|
Getatime () |
Return last access time |
Getctime () |
Return file creation time |
Getmtime () |
Return file modification Time |
GetSize () |
Return file size |
Inquire |
|
Exists () |
Specifies whether the path exists |
Isabs () |
Specifies whether the path is an absolute path |
Isdir () |
Specifies whether the path exists and is a directory |
Isfile () |
Specifies whether the path exists and is a file |
Islink () |
Specifies whether the path exists and is a symbolic link |
Ismount () |
Specifies whether the path exists and is a mount point |
Samefile () |
Two path names pointing to the same file |
End
Finally end this blog with an example of Python core programming
#!/usr/bin/env PythonimportOS forTmpdirinch('/tmp ',' C:/windows/temp '):if OS. Path.isdir (Tmpdir): BreakElse:Print ' No temp directory available 'Tmpdir ="'ifTmpdirOS. ChDir (tmpdir) CWD =OS. GETCWD ()Print ' * * * Current temporary directory ' PrintCwdPrint ' * * * * Creating example Directory ... ' OS. mkdir (' Example ')OS. ChDir (' Example ') CWD =OS. GETCWD ()Print ' * * * New working directory: ' PrintCwdPrint ' * * * original directory listing: ' Print OS. Listdir (CWD)Print ' * * * * Creating test file ... 'File = Open (' Test ',' W ') File.write (' foo\n ') File.write (' bar\n ') File.close ()Print ' * * * updated directory listing: ' Print OS. Listdir (CWD)Print "* * * * renaming ' test ' to ' filetest.txt '" OS. Rename (' Test ',' Filetest.txt ')Print ' * * * updated directory listing: ' Print OS. Listdir (CWD) path =OS. Path.join (CWD,OS. Listdir (CWD) [0])Print ' * * * full file pathname: ' PrintPathPrint ' * * * (pathname, basename) = = ' Print OS. Path.split (Path)Print ' * * * (filename, extension) = = ' Print OS. Path.splitext (OS. Path.basename (Path))Print ' * * * * displaying file contents: 'File = open (path) Alllines = File.readlines () file.close () forEachlineinchAlllines:PrintEachline,Print ' * * * deleting test file ' OS. Remove (Path)Print ' * * * updated directory listing: ' Print OS. Listdir (CWD)OS. ChDir (OS. Pardir)Print ' * * * deleting Test directory ' OS. RmDir (' Example ')Print ' * * * done '
Output Results (Linux)
Likai@likai-lenovo-g490:~/python$pythonospathex.py*** Current Temporary Directory/tmp*** Creating Example Directory ...*** New Working Directory:/tmp/example*** Original Directory listing:[]*** Creating testfile...*** Updated Directory listing:[' Test ']*** Renaming' Test 'To' Filetest.txt '*** Updated Directory listing:[' Filetest.txt ']*** Fullfilepathname:/tmp/example/filetest. txt*** (Pathname,basename) == ('/tmp/example ',' Filetest.txt ')*** (filename, extension) = = (' Filetest ','. txt ')*** DisplayingfileContents:foobar*** Deleting testfile*** Updated directory listing:[]*** Deleting Test directory*** Done
Python Learning Path 19-File IO