Python Files and directories (chapter III: Files and directories)

Source: Internet
Author: User
Tags glob parent directory

This chapter describes the functions and types used in Python to read and write files and access directory content. Python provides a rich set of input and output functions, which are described in this chapter by using a wide range of functions, starting with the file object, which is the basic method for implementing input and output in Python, and then describes the functions for manipulating paths, obtaining file information, and accessing directory content.

3.1 File objects

In the Windows path name, you must escape in the path squadron backslash, i.e. use two backslashes each time, for example, path C:\windows\temp, c:\\windows\\temp with Python string, or place a R to cancel the string special handling of the squadron backslash, R "C:\windows\temp".

3.1.1 Writing a text file

Starting with creating a simple text file, you create a file object that tells P that you want to write to the file, that the file object represents a link to a file, not the price itself, but if you try to open or write data like a nonexistent file, Python will automatically create it.

>>>def  make_text_file ():        a= open ('text.txt'," W " )        a.write ("This is what youcreate a new text file")        a.close () 

You can start by creating a make-text-file () function and tell Python to begin a file named Test.txt. Since Python cannot find the file, it creates it on its own, noting that if the file exists, Python will delete it and create a new one, followed by how to check if it already exists before you create a file.

Below we create a program that first checks if a file already exists and returns an error message if one exists.

>>>ImportOS>>>defmake_another_file ():ifOs.path.isfile ('Test.txt'):        Print("You is trying to create a file that already exists!")    Else: F= Open ("Test.txt","W") F.write ("How do you create a new text file")...>>>Make_another_file ()"You is trying to create a file that already exists!"

When opening a file, you can create a relative path or an absolute path using the other file-handling functions discussed in this chapter.

3.1.2 Append text to Text

Appending text to a file is easy to implement, and appending text is not implemented with the parameter "W", but with the append parameter "a". This ensures that the data already in the file is not rewritten, but instead appends the new text to the end of the file and tries the following code:

>>>def  Add_some_text ():        = open ('test.txt'," a " )        a.write ("here issome additional text! " )... >>>add_some_text ()

Note that the write function is not wrapped automatically, so I'm going to use the escape sequence \ n.

3.1.3 Degree text file

Read the file is similar, first, by creating a file object to open the files, this time, using "R" to tell Python to read the file, "R" is the default parameter, can be omitted.

    A = open ("text.txt","R")

You can use the ReadLine method to read a line of text from a file

>>>a.readline ()"blablablabla ... "

You can also use the Read method to read the rest of the file at once, which returns everything that is not read in the file.

>>>f= Open ("test.txt","R")>>> text=a.read ()>>> is

When you're done, delete the file object and close

>>>del  a>>>a.close ()

3.2 Paths and directories

3.3os exception

The function in the OS module throws a OSError exception when it fails, and if you want the program to behave in a friendly way when it goes wrong, you must handle the exception, and as with IOError, the string representation of the exception describes the problem encountered.

3.3.1 Path

The OS contains another module, Os.path, which provides functions for manipulating paths.

3.3.2 Directory Contents

How to find what actually exists on the hard disk, the Os.listdir module returns all the name entries in a directory, including the contents of files and subdirectories.

Get directory Contents

>>>os.listdir ("c:\\python31") [Blablablabla]

List the contents of the desktop or home directory

Use Print_dir_by_ext to list the contents of the desktop or home directory. The desktop of Windows is a folder, and its movie path is C:\\Documents and Settings\\username\\desktop, where username is the account name.

3.3.3 Getting file information

It is easy to tell if a file is pointing to a file or to a directory, and if it is pointing to a file, Os.path.isfile will return true if it is pointing to the directory, Os.path.isdir will return true.

Other types of directory entries

Under some platforms, a directory may contain many other types of entries, such as symbolic links, sockets, and devices, and the specific meanings of these types of entries depend on the specific platform.

Recursive directory list

You can combine Os.path.isdir and os.listdir, for example, recursively processing subdirectories, listing the contents of a directory, its subdirectories, subdirectories, and so on, and, for this purpose, writing a recursive function is useful.

Note that the above function is similar to the previously written Print_dir function. However, this function constructs a full path full_path for each entry, as this is in line with the printing requirements and also takes into account the subdirectory requirements

3.3.4 renaming, moving, copying and deleting files

The function of the action file is included in the module SHUTIL. You can rename a file with Shutil.move:

Alternatively, you can use it to move a file to another directory:

The Shutil module also provides a copy function that sees a file copied to a file with a new name, or a new directory, which can be simply used as follows:

The deletion is:

If you are going to give old-fashioned UNIX hackers, you can use Os.unlink to do it.

File permissions

File permissions work differently on different platforms, but if you need to change the permissions of a file or directory, you can use the Os.chmod function, which works the same way that UNIX or Linux systems invoke chmod.

3.3.5 Rotate Files

3.3.6 Creating and deleting directories

You can do this when you create a call to Os.mkdir, but the parent path of the directory you want to create first exists. Otherwise an exception will occur:

>>>os.mkdir ("c:\\photos\\zoo\\snakes")

You can use Os.makedirs, which can create a nonexistent parent directory, for example, the following code will create C:\\photos and C:\\photos\zoo in Ethiopia.

>>>os.makedirs ("c:\\photos\\zoo\\snakes")

Use function Os.rmdir ("C:\\photos\\zoo\\snakes")

The above code will only remove snakes

Instead, Shutil.rmtree can delete other files and subdirectories that are contained in the directory. Use caution when you pass in an error path that deletes a set of files, and you don't even know what's going on. For example, the following code removes the complete picture set, including the Zoo,snakes

3.3.8 Pass

If you have ever used a Windows-system cmd or a shell such as an operating system such as Gun/linux, you may have seen a wildcard pattern, with some special characters such as * and? , you can use them to match many files with similar names. For example, use pattern p* to match all files that begin with the name P, *.txt is the suffix. txt file.

Wildcard is case-insensitive

We tried to find the entry for M, using Glob.glob to return the path to the matching pattern containing the disk driver and directory name.

Here, other wildcard characters are provided:

Python Files and directories (chapter III: Files and directories)

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.