Python file manipulation techniques (file operation) Instance code analysis

Source: Internet
Author: User
The usual module is OS, Os.path and Shutil, so introduce them first.

python traversing folders and files
This is perhaps the most commonly used feature, as follows:

The code is as follows:


Import OS
Import Os.path

RootDir = "D:\\programmer\\training"
For the parent, Dirnames, filenames in Os.walk (RootDir):
#case 1:
For dirname in Dirnames:
Print "Parent is:" + Parent
Print "DirName is:" + dirname
#case 2
For filename in filenames:
Print "Parent is:" + Parent
print "FileName with full path:" + os.path.join (parent, filename)


Explanatory notes:

1.os.walk returns a ternary group. Where Dirnames is the name of all the folders (without the path), filenames is the name of all the files (not including the path). The parent represents the parents directory.
2.case1 shows how to traverse all the directories.
3.case2 demonstrates how to traverse all the files.
4.os.path.join (Dirname,filename): Turns the form "/a/b/c" and "D.java" into/a/b/c/d.java ".


perl split path and file name
There are three common functions: separating the path to find the file name. Find the drive letter (Windows system) and find out the file extension.

The code is as follows:


Import Os.path

Spath= "D:/download/flight/flighthtml.txt"

# case 1:
P,f=os.path.split (spath);
Print "DIR is:" +p
Print "File is:" +f

# case 2:
Drv,left=os.path.splitdrive (spath);
Print "Driver is:" +drv
Print "Left is:" +left
# Case 3:
F,ext=os.path.splitext (spath);
Print "F is:" +f
Print "ext is:" +ext


Each of these three functions returns a two-tuple.
1.case1 separating directories and filenames
2.CASE2 Separator Letter and file name
3.case3 Delimited files and extensions
  • 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.