Python Learning Notes (25) manipulating files and directories

Source: Internet
Author: User
Tags posix

Excerpt: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001431925324119bac1bc7979664b4fa9843c0e5fcdcf1e000

Python's built-in os modules can also directly invoke the interface functions provided by the operating system.

Import OS # Operating System Type ' NT '

If yes posix , the system is Linux , Unix or Mac OS X , if it is, the nt Windows system.

To get detailed system information, you can call the uname() function:

  >>> Os.uname () posix.uname_ result (sysname  = darwin   ' , Nodename= " michaelmacpro.local  , Release="  14.3.0  , Version="  darwin Kernel Version 14.3.0:mon Mar 11:59:05 PDT 2015; root:xnu-2782.20.48~5/release_x86_64  , machine=   x86_64   )   

Note that uname() functions are not available on Windows, that os is, some functions of the module are related to the operating system.

Environment Variables

The environment variables defined in the operating system are all stored os.environ in this variable and can be viewed directly:

>>>Os.environenviron ({'Versioner_python_prefer_32_bit':'No','term_program_version':'326','LOGNAME':'Michael','USER':'Michael','PATH':'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/x11/bin:/usr/local/mysql/bin', ...})

To get the value of an environment variable, you os.environ.get(‘key‘) can call:

>>> os.environ.get ('PATH')'/usr/bin:/bin:/usr/sbin:/ Sbin:/usr/local/bin:/opt/x11/bin:/usr/local/mysql/bin'>>> os.environ.get ('  x'default')'default' 
manipulating files and directories

It is important to note that part of the function for manipulating files and directories is placed in the os module and part os.path of the module. viewing, creating, and deleting directories can be called:

#to view the absolute path of the current directory:>>> Os.path.abspath ('.')'/users/michael'#To create a new directory under a directory, first represent the full path to the new directory:>>> Os.path.join ('/users/michael','TestDir')'/users/michael/testdir'#then create a directory:>>> Os.mkdir ('/users/michael/testdir')#Remove a directory:>>> Os.rmdir ('/users/michael/testdir')

To synthesize two paths, do not spell the string directly, but pass the os.path.join() function so that the path delimiter of the different operating systems can be handled correctly. Under Linux/unix/mac, os.path.join() return such a string:

Part-1/part-2

and Windows will return such a string:

Part-1\part-2

Similarly, to split a path, do not go directly to the string, but through os.path.split() the function, so that a path can be split into two parts, the latter is always the last level of the directory or file name:

>>> os.path.split (  /users/michael/testdir/file.txt   " ) (   " /users/michael/testdir   ' ,  " file.txt   '   ' Os.path.splitext () you can get the file extension directly, many times very convenient:  >>> os.path.splitext ('/path/to/file.txt '  )  (  " /path/to/file  , "  .txt  ) 

These functions of merging and splitting paths do not require directories and files to be real, they operate only on strings.

The file operation uses the following function. Assume that there is a file in the current directory test.txt :

# Renaming files:>>> os.rename ('test.txt'test.py  ')# Erase files:>>> os.remove ('test.py' )

the function of copying a file os does not exist in the module ! The reason is that the copy file is not a system call provided by the operating system. Fortunately, the shutil copyfile() functions provided by the module , you can also shutil find a lot of practical functions in the module, they can be seen as a complement to os the module.

Finally, see how to filter files using Python's features . For example, we want to list all the directories in the current directory , just one line of code:

>>> [x forXinchOs.listdir ('.')ifOs.path.isdir (x)] ['. Lein','. Local','. M2','. NPM','. SSH','. Trash','. Vim','Applications','Desktop', ...]

To list all the .py files, just one line of code:

>>> [x forXinchOs.listdir ('.')ifOs.path.isfile (x) andOs.path.splitext (x) [1]=='. PY']['apis.py','config.py','models.py','pymonitor.py','test_db.py','urls.py','wsgiapp.py']
Summary

Python's os modules encapsulate the operating system's directory and file operations, and note that some of these functions are in os modules, some in os.path modules.

Practice
    1. Use os the module to write a dir -l program that implements the output.

    2. Write a program that finds the file name containing the specified string in the current directory and all subdirectories of the current directory, and prints a relative path.

 fromDatetimeImportdatetimeImportospwd= Os.path.abspath ('.')Print('Size last Modified Name')Print('------------------------------------------------------------') forFinchOs.listdir (PWD): Fsize=os.path.getsize (f) mtime= Datetime.fromtimestamp (Os.path.getmtime (f)). Strftime ('%y-%m-%d%h:%m') Flag='/' ifOs.path.isdir (f)Else "'    Print('%10d%s%s%s'% (Fsize, mtime, F, flag))

Python Learning Notes (25) manipulating files and directories

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.