File path
The file has two key properties: "File name" and "path". The path indicates the location of the file on the computer.
On Windows, path writing uses a backslash as a delimiter between folders. But on OS X and Linux, forward slashes are used as their path delimiters. If you want the program to run on all operating systems, you must handle both cases when writing a Python script.
If you pass a string of folder names on a single file and path to the Os.path.join () function, it returns a string of file paths containing the correct path delimiter.
>>> Import os>>> os.path.join (' usr ', ' local ', ' src ', ' mysql ') ' Usr/local/src/mysql '
All file names or paths that do not start from the root folder are assumed to be under the current working directory. With the OS.GETCWD () function, you can get a string of the current working path and change it with Os.chdir ().
If the current working directory you want to change does not exist, Python will display an error.
>>> import os>>> os.getcwd () '/root ' >>> os.chdir ('/usr/local/') >>> os.getcwd () '/ Usr/local '
You can create a new directory with the Os.makedirs () function. It creates all the necessary intermediate folders to ensure that the full path name exists.
>>> Import os>>> os.makedirs ('/tmp/newdir ')
Absolute path and relative path
▎ There are two ways of specifying a file path:
Absolute path, always starting from the root folder.
Relative path, which is relative to the current working directory of the program.
"." When used as a folder directory name, it is the abbreviation for "This directory".
".." It means the parent folder.
>>> os.getcwd () '/usr/local ' >>> os.chdir ('./src ') >>> os.getcwd () '/usr/local/src '
Os.path Module
The Os.path module contains many useful functions related to filenames and file paths. Because Os.path is a module in the OS module, it can be imported as long as the import OS is executed.
The Os.path module provides functions that return an absolute path to a relative path and check whether a given path is an absolute path.
Call Os.path.abspath (path) to return the string for the absolute path of the parameter. This is an easy way to convert a relative path to an absolute path.
Call Os.path.isabs (path), returns True if the argument is a 1 absolute path, or false if the argument is a relative path.
Calling Os.path.relpath (Path,start) returns a string from the start path to the path's relative paths. If start is not provided, the current working directory is used as the start path.
>>> Os.path.abspath ('./src ') '/usr/local/src ' >>> os.path.isabs ('./src ') false>>> Os.path.relpath ('/tmp/') '. /.. /tmp '
Calling Os.path.dirname (Path) returns a string that contains everything before the last slash in the path parameter.
Calling Os.path.basename (Path) returns a String that contains everything after the last slash in the path parameter.
If you need both a directory name and a base name for a path, you can call Os.path.split () to get the tuples for both strings.
Os.path.split () does not accept a file path and returns a list of strings for each folder.
The split () string method returns a list that contains all the parts of the path. If you pass os.path.sep to it, you will be able to work on all operating systems.
>>> os.path.dirname ('/usr/local/src/mysql ') '/usr/local/src ' >>> os.path.basename ('/usr/local/ Src/mysql ') ' MySQL ' >>> os.path.split ('/usr/local/src/mysql ') ('/usr/local/src ', ' MySQL ')
The call to Os.path.getsize (path) returns the number of bytes of the file in the path parameter.
Calling Os.listdir (path) Returns a list of file name strings, containing each file in the path parameter.
>>> Import os>>> os.path.getsize ('/tmp/1.txt ') 1100>>> os.listdir ('/tmp/') ['. Font-unix ', ‘. X11-unix ', '. Ice-unix ', '. Test-unix ', '. Xim-unix ', ' py.py ', ' bigfile ', ' yum_save_tx.2017-07-20.09-37.lxnivf.yumtx ', ' newdir ', ' 1.txt '
The Os.path module provides functions to detect the existence of a given path and whether it is a file or a folder.
If the file or folder that the path parameter refers to exists, calling os.path.exists (path) returns True, otherwise false is returned.
If the path parameter exists and is a file, calling Os.path.isfile (path) returns True, otherwise false is returned.
If the path parameter exists and is a folder, calling Os.path.isdir (path) returns True, otherwise false is returned.
Using the os.path.exists () function, you can determine whether a DVD or flash drive is currently connected to your computer.
>>> os.path.exists ('/tmp/1.txt ') true>>> os.path.isfile ('/tmp/1.txt ') true>>> Os.path.isdir ('/tmp/1.txt ') False
File read and write process
Plain text files contain only basic text characters and do not contain font, size, and color information.
"Binaries" are all other file types, such as word-processing documents, PDFs, images, spreadsheets, and executable programs.
▎ in Python, there are 3 steps to reading and writing a file:
1. Call the open () function to return a file object.
2. Call the Read () or write () method of the File object.
3. Call the Close () method of the file object to close it.
When you open a file in Python, the read mode is the default mode. "R" indicates read mode, "W" indicates write mode, "a" indicates add mode.
If the file name passed to open () does not exist, both write mode and add mode will create a new empty file. After the file is read or written, the close () method is called before the file can be opened again.
If the contents of the file are treated as a single large string, the read () method returns the string that is stored in the file.
You can also use the ReadLines () method to get a list of strings from a file. Each string in the list is each line of text.
The Write () method does not automatically add a newline character to the end of a string, like the print () function 1. You must add the character yourself.
>>> readfile=open ('/tmp/1.txt ') >>> txt=readfile.read () >>> txt ' 123~ 112313213\nroot:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/ Nologin\nadm:x:3:4:adm:/var/adm:/sbin/nologin\nlp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\nsync:x:5:0:sync:/sbin :/bin/sync\nshutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\nhalt:x:7:0:halt:/sbin:/sbin/halt\nmail:x:8:12:mail:/ var/spool/mail:/sbin/nologin\noperator:x:11:0:operator:/root:/sbin/nologin\ngames:x:12:100:games:/usr/games:/ Sbin/nologin\nftp:x:14:50:ftp user:/var/ftp:/sbin/nologin\nnobody:x:99:99:nobody:/:/sbin/nologin\ Nsystemd-bus-proxy:x:999:998:systemd bus proxy:/:/sbin/nologin\nsystemd-network:x:192:192:systemd network management:/:/sbin/nologin\ndbus:x:81:81:system message bus:/:/sbin/nologin\ Npolkitd:x:998:997:user for polkitd:/:/sbin/nologin\ntss:x:59:59:account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin\nsshd:x:74:74:privilege-separated ssh:/var/empty/sshd:/sbin/nologin\npostfix:x:89:89::/var/spool/postfix:/sbin/nologin\nchrony:x:997:995: :/var/lib/chrony:/sbin/nologin\ntcpdump:x:72:72::/:/sbin/nologin\njuispan:x:1000:1000::/home/juispan:/bin/bash \ n ' >>> readfile.close ()
Save variables
With the shelve module, you can save variables in a Python program to a binary shelf file. This allows the program to recover variable data from the hard disk.
The shelve module equals the Add "save" and "open" functions in the program.
The shelf values do not have to be opened in read or write mode because they are both readable and writable when they are opened.
Like a dictionary, the shelf value has the keys () and the values () method. Returns a list-like value instead of a real list.
>>> Import shelve>>> shelfile=shelve.open (' MyData ') >>> price=[1,2,3]>>> shelfile[' Price ']=price>>> shelfile.close () >>> shelfile=shelve.open (' MyData ') >>> type ( Shelfile) <class ' shelve. Dbfilenameshelf ' >>>> list (Shelfile.keys ()) [' Price ']>>> list (shelfile.values ()) [[1, 2, 3]]> >> shelfile[' price '][1, 2, 3]>>> shelfile.close ()
You can save the variable with the Pprint.pformat () function.
The import statement imports the module itself as a Python script.
>>> Import pprint>>> price=[1,2,3,4,5]>>> pprint.pformat (Price) ' [1, 2, 3, 4, 5] ' >> > Pfile=open (' pprice.py ', ' W ') >>> pfile.write (Pprint.pformat (price)) 15>>> Pfile.close ()
You can see the contents of the file by importing the pprice.py module. The advantage of creating a. py file is that because it is a text file, anyone can read and modify the contents of a file with a simple text editor. However, for most applications, using the shelve module to save data is the best way to save variables to a file. Only basic data types, such as Integer, float, string, list, and dictionary, can be written to a file as simple text.
This article is from the "Technician Training Manual" blog, please be sure to keep this source http://juispan.blog.51cto.com/943137/1949918
[Python 3 Series] Read and write files