Python file manipulation techniques (file operation) instance code analysis _python

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

python traverses folders and files
This is probably the most commonly used feature, as follows:
Copy Code code as follows:

Import OS
Import Os.path

RootDir = "D:\\programmer\\training"
For 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)

EXPLANATION Note:

1.os.walk returns a ternary group. Where Dirnames is the name of all folders (without paths), filenames is the name of all files (without paths). Parent represents the parents directory.
2.case1 demonstrates how to traverse all directories.
3.case2 demonstrates how to traverse all the files.
4.os.path.join (Dirname,filename): will be shaped like "/a/b/c" and "D.java" into/a/b/c/d.java.


perl split path and filename
There are three common functions: separating the path and finding the filename. Find the letter (Windows System) and find the file extension.
Copy Code code 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

All three functions return a two-tuple.
1.case1 Delimited directory and filename
2.CASE2 Separator Letter and filename
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.