Python's actions on files and folders

Source: Internet
Author: User

The operation of files and folders in Python involves both the OS module and the Shutil module.

To create a file:
1) Os.mknod ("Test.txt") Create an empty file
2) Open ("Test.txt", W) opens a file directly and creates a file if the file does not exist

To create a directory:
Os.mkdir ("file") Create directory

To copy a file:
Shutil.copyfile ("Oldfile", "NewFile") Oldfile and NewFile can only be files
Shutil.copy ("Oldfile", "NewFile") Oldfile can only be a folder, NewFile can be a file, or it can be a destination directory

To copy a folder:
Shutil.copytree ("Olddir", "Newdir") Olddir and Newdir can only be directories, and newdir must not exist

Renaming files (directories)
Os.rename ("Oldname", "newname") files or directories are all using this command

Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")

deleting files
Os.remove ("file")

Delete Directory
Os.rmdir ("dir") can only delete empty directories
Shutil.rmtree ("dir") empty directory, contents of the directory can be deleted

Converting catalogs
Os.chdir ("path") Change path

Judging the target
Os.path.exists ("goal") to determine if the target exists
Os.path.isdir ("goal") determine whether the target directory
Os.path.isfile ("goal") determine if the target is a file

Category: Python

Python's actions on files and folders

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.