Python Operations files and directories

Source: Internet
Author: User

Import Osos.name # Operating system name Os.environ #版本 # to get the value of an environment variable, you can call the Os.getenv () function os.getenv (' PATH ')
Manipulating Files and directories:

Part of the function of manipulating files and directories is placed in the os module, part of the os.path module

# View the absolute path of the current directory: Os.path.abspath ('. ') ' /users/michael ' # Create a new directory under a directory, # First, the full path of the new directory is represented: 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 ')

os.path.join()Functions: Merging paths

os.path.splitext()Allows you to get the file name extension directly

# Rename File: Os.rename (' test.txt ', ' test.py ') # Delete file: Os.remove (' test.py ')

shutilmodule provides copyfile() functions, you can also shutil find a lot of practical functions in the module, they can be seen as a os complement to the module

List all directories in the current directory

[x for X in Os.listdir ('. ') if Os.path.isdir (x)] ['. Lein ', '. Local ', '. M2 ', '. npm ', '. ssh ', '. Trash ', '. Vim ', ' adlm ', ' applications ', ' Desktop ', ...]

Lists the. py files under the current path

[x for X in Os.listdir ('. ') if Os.path.isfile (x) and Os.path.splitext (x) [1]== '. Py '] [' apis.py ', ' config.py ', ' models.py ', ' pymonitor.py ', ' test_db.py ', ' urls.py ', ' wsgiapp.py ']

  

 

Python Operations files and directories

Related Article

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.