Python renaming and deleting file definitions and functions (instance analysis)

Source: Internet
Author: User
Today in this article we look at the renaming and deletion of files in Python, as the name implies, this article is mainly about Python renaming files and python delete files two points of knowledge.

Renaming and deleting files

Python's OS module provides a way to help you perform file processing operations, such as renaming and deleting files.

To use this module, you must first import it before you can invoke the various functions associated with it.

Rename () Method:

The rename () method requires two parameters, the current file name, and a new filename.

The syntax is as follows:

Os.rename (Current_file_name, New_file_name)

Example:

The following example renames a file that already exists test1.txt.

#!/usr/bin/python#-*-coding:utf-8-*-import os# rename file Test1.txt to Test2.txt. Os.rename ("Test1.txt", "Test2.txt")

Remove () method

You can delete the file using the Remove () method, and you need to provide the filename to delete as a parameter.

Grammar:

Os.remove (file_name)

Example:

The following example deletes a file that already exists test2.txt.

#!/usr/bin/python#-*-coding:utf-8-*-import os# Delete an existing file Test2.txtos.remove ("Test2.txt")
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.