Interpreting the processing file in Python

Source: Internet
Author: User

How to copy and delete files in the Python language, and how to break down a complete file path into a directory part and a file name part. Finally, we will explain how to create a directory, and how to move directories and process files in the directory tree.

Although file and directory processing can be completed by operating system commands, the Python language allows developers to process related work in a programming manner, provides many built-in functions for processing files and directories. Importantly, these functions are used in the same way on Unix, Windows, and Macintosh platforms. This article will explain in detail how to use these functions.

First, we will introduce the file listing function in Python, which is similar to the dir command in Windows, and then describe how to test whether a file name corresponds to a standard file, directory, or link, and how to extract the file size and date.

After that, we will also introduce how to delete files and directories, copy and delete files, and how to break a complete file path into a directory part and a file name part. Finally, we will explain how to create directories and how to move directories and process files in the directory tree.

1. display the directory content when we want to list the contents in the current directory:

 
 
  1. Origdir=OS. Getcwd () # Write down the current location
  2. Newdir=OS. Path. join (OS. pardir, 'mynewdir ')
  3. If not OS. path. isdir (newdir ):
  4. OS. mkdir (newdir) # Or OS. mkdir (newdir, '123 ')
  5. OS. chdir (newdir)
  6. ...
  7. OS. chdir (origdir) # return to the original directory
  8. OS. chdir (OS. environ ['home']) # Move to the main directory

The code above uses the glob function. The parameter of this function is the file type to be displayed. Here, the file type is specified by some file names similar to the shell-style wildcard descriptions in the UNIX operating system. For more information about how to use these wildcards, see the document of the fnmatch module. To display all files in a directory, you can use the OS. listdir function as follows:

 
 
  1. Def checksize1 (arg, dirname, files ):
  2.  
  3. For file in files:
  4.  
  5. Filepath=OS. Path. join (dirname, file)
  6.  
  7. If OS. path. isfile (filepath ):
  8.  
  9. Size=OS. Path. getsize (filepath)
  10.  
  11. If size>1000000:
  12.  
  13. SizeSize_in_Mb= Size/1000000.0
  14.  
  15. Arg. append (size_in_Mb, filename ))
  16.  
  17. Bigfiles= []
  18.  
  19. Root=OS. Environ ['home']
  20.  
  21. OS. path. walk (root, checksize1, bigfiles)
  22.  
  23. For size, name in bigfiles:
  24.  
  25. Print name, 'size is ', size, 'mb'

We know that the file name, directory name, and link name all use a string as its identifier, but give us an identifier, how can we determine whether it refers to a regular file name, directory name, or link name? In this case, we can use the isfile function, isdir function, and islink function provided by the OS. path module to achieve our goal.

To delete a single file, you can use the OS. remove function, for example, OS. remove ('mydata. dat '). The alias for OS. remove IS OS. unlink. However, the latter name is the same as the traditional UNIX operating system and the function for clearing files in Perl. You can delete a group of files by using the following formula, such as all files with the extension of .jpg and *. gif:

 
 
  1. def somefunc(arg, dirname, files):  
  2. origdir = os.getcwd(); os.chdir(dirname)  
  3. <do tasks> 
  4. os.chdir(origdir)  
  5. os.path.walk(root, somefunc, arg) 

As you know, you can use the rmdir command to delete a directory only when its content has been cleared. However, we often want to delete a directory tree containing many files. In this case, we can use the rmtree function provided by the shutil module, as shown below:

 
 
  1. def somefunc(arg, dirname, files):  
  2. origdir = os.getcwd(); os.chdir(dirname)  
  3. <do tasks> 
  4. os.chdir(origdir)  
  5. os.path.walk(root, somefunc, arg) 

It is actually too strict. All we need is a file/directory name sequence that is traversed. In fact, we do not care whether the name is stored in a list, tuples, or numeric array. Therefore, a better test should be like the following:

Suppose we want to create a new directory py/src/test1 under our home directory, but neither py, src nor test1 currently exists. If you use the mkdir command to create an image. This nested directory can be created three times, but you do not need to worry about using the OS. makedirs Command provided by Python. This command can be used to create the entire directory at one time.

  1. Introduction to Python system files
  2. How to correctly use Python Functions
  3. Detailed introduction and analysis of Python build tools
  4. Advantages of Python in PythonAndroid
  5. How to Use the Python module to parse the configuration file?

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.