Python Study Notes (7)

Source: Internet
Author: User

Directory and file operations

A language can only be connected to external entities for more powerful functions, such as operating files and databases. In this way, data can be stored separately instead of in the memory. More powerful is network programming, of course, these will be learned later. Next, we will learn how to operate directories and files in python. The previous notes are basic theoretical knowledge. I think we can do something from here.

You can find and delete folders and files inOSModule. Import OS

Directory

1. Get the current directory-OS. getcwd ()

>>> Import OS >>> s = OS. getcwd () # obtain the directory where the current running script is located >>> s 'C: \ python27'

For example, if you run test. py, enter this command to return the folder location where the script is located.

For example, put test. py in the folder. In addition, you can create A new folder in folder A regardless of the location of folder A on the hard disk. The folder name is automatically generated based on the time.

>>> Import OS >>> import time >>> folder = time. strftime (r "% Y-% m-% d _ % H-% M-% S", time. localtime () >>>OS. makedirs(R '% s/% s' % (OS. getcwd (), folder) # create a folder named after time

This is the directory for running the script, that is, a folder named after the current time is added under 'C: \ python27 '.

2. Create a subdirectory-OS. makedirs ("path"). path is the subdirectory to be created.

>>> OS. makedirs ("C: \ temp \ test") # The temp directory is created under drive C. The nested folder in temp is test.

(Of course, creation may also fail, for example, the path already exists, the drive is not there, or you have no write permission)

3. Change the current directory-OS. chdir ()

It is equivalent to a cd command in dos or Linux.

>>> OS. chdir ('C: \ ') # change the current directory to the c root directory.

4. Break down the path into the directory name and file name-OS. path. split ()

Format: fpath, fname = OS. path. split ("path to be decomposed ")

>>> a,b=os.path.split("c:\\dir1\\dir2\\file.txt")>>> print ac:\dir1\dir2>>> print bfile.txt

5. Split the file name extension-OS. path. splitext ()

Format: fpath_name, ftext = OS. path. splitext ("path to be decomposed ")

>>> a,b=os.path.splitext("c:\\dir1\\dir2\\file.txt")>>> print ac:\dir1\dir2\file>>> print b.txt

6. Determine whether a path (directory or file) exists -- OS. path. exists ()

Format: OS. path. exists ("path or file to be determined ")

>>> OS. path. exists ("C :\\") # This path exists. True >>> OS. path. exists ("C: \ 123 \") # This path does not exist False >>> OS. path. exists ("C :\\ 123.txt") # This file does not exist False >>> OS. path. exists ("C: \ test.txt") # This file exists True

7. Determine whether a required file exists in a path-OS. path. isfile ("file ")

>>> os.path .isfile("C:\\test.txt")True>>> os.path .isfile("C:\\123.txt")False

8. Determine whether a path exists-OS. path. isdir ("path ")

>>> os.path .isdir("C:\\")True>>> os.path .isdir("H:\\")False

9. Get the list of files and subdirectories in the directory-OS. listdir ("path ")

It is equivalent to the Get-ChildItem command in Windows powershell and the ls command in Linux. However, this display is not in the form of a common list:

>>> OS. listdir ("C :\\") # The hidden files are shown in ['$ Recycle. bin', '360ld ', '360rescue', '360sandbox', '360sysrt', 'boot', 'bootmgr ', 'bootsect. BAK ', 'cachetemp', 'documents and settings', 'grldr', 'IFRToolLog.txt', 'inetpub', 'msocac', 'pagefile. sys ', 'program files', 'program Files (x86)', 'gramdata', 'python27', 'recovery ', 'recycler', 'sbtdr ', 'System Volume information', 'test.txt ', 'users', 'windows']

Example: retrieve the list of all subdirectories in a specified directory

View Code

Obtains the list of all objects in a specified directory.

View Code

10. Delete the subdirectory-OS. rmdir ("path"). Only empty directories can be deleted.

>>> OS. rmdir ("C: \ temp \ test") # Delete only the test directory >>> OS. rmdir ("C: \ temp") # The temp directory is deleted here.

File

The introduction of modules in python makes file operations easy. The most basic file operation is to read and write data in the file and open the file before operating the file.

Open the file -- open ('file' [, 'Mode'])

>>> Import OS
>>> OS. getcwd () 'C: \\' >>> file=open('test.txt ') # The default mode is 'R', that is, the Read mode >>> file. read () # read the file content 'Hello \ nworld \ nhello, python' # \ n in the form of a line break in the file

The meaning of the mode option is as follows:

Model

Description

R

Open the file in Read mode to read the file information.

W

Open the file in write mode and write information to the file. If the file exists, the file is cleared and new content is written. If the file does not exist, the file is created.

A

Open the file in append mode (when the file is opened, the file pointer is automatically moved to the end of the file). If the file does not exist, create

R +

Open a file in read/write mode to read and write the file.

W +

Remove the file content and open the file in read/write mode.

A +

Open the file in read/write mode, and move the file pointer to the end of the file.

B

Open the file in binary mode, instead of text mode. This mode is only valid for Windows or Dos, and Unix-like files are operated in binary mode.

I think there is no need to record other file operations in detail, because they are basically very simple. The common methods of files are listed below, and relevant instructions are provided in the example. In addition, it is important to note that the encoding problem frequently exists in reading files. The default codes of different interpreters are different. The specific solution will be described later.

Common file operations:

Method

Description

F. close ()

Close the file. Remember to close the file after opening it with open (). Otherwise, it will occupy the number of accessible file handles of the system.

F. name ()

Get File Name

F. next ()

Return to the next row, and move the operation mark of the file to the next row. Use a file... When a statement such as in file is called, the next () function is called to implement traversal.

F. fileno ()

Obtains the file descriptor, which is a number. Returns a long integer "file tag".

F. flush ()

Refresh the output cache and write the buffer content to the hard disk.

F. isatty ()

If the file is a terminal device file (in Linux), True is returned; otherwise, False is returned.

F. read ([size])

Read the file. The size is the read length, in bytes.

F. readline ([size])

Read the information of a row. If the size is defined, read part of the row.

F. readlines ([size])

Read all rows, that is, read the information of the entire file. (Use each row of the file as a member of a list and return this list. In fact, it is implemented by calling readline () cyclically. If the size parameter is provided, size indicates the total length of the read content, that is, it may be read only to a part of the file)

F. seek (offset [, where])

Move the file pointer to the offset position relative to where. Where 0 indicates the start of the file, which is the default value; 1 indicates the current position; 2 indicates the end of the file. (Note: If the file is opened in a or a + mode, the file operation mark will be automatically returned to the end of the file each time the write operation is performed)

F. tell ()

Get the file pointer position, mark the current position, start with the file as the origin

F. truncate ([size])

Crop the file to a specified size. The default value is the location marked by the current file operation. If the size is larger than the file size, the file may not be changed depending on the system, or 0 may be used to fill the file with the corresponding size, it may also be added with random content.

F. write (string)

Writes a string to a file. write () does not add a linefeed after str.

F. writelines (list)

Writing a string in the list into a file row by row is a continuous write to the file without line breaks.

There is a test.txt file in the following format:

?
helloworldhellopython

The following are some common operations:

>>> Fileinto open('test.txt ') >>> file. read (4) # read the first 4 bytes 'hangel' >>> file. read (6) # Note: Here is the 'o \ nworl '> file that is read backward based on what you have just read. read () # If no size is specified, the end of the file 'd \ nhello \ npython' >>> file. read () # The End Of The file ''> file. seek (0) # locate the file to the first byte> file. readline () # Read a row 'Hello \ n'> file. readline () 'World \ n' >>> file. seek (0) # locate the file to Start> file. readlines () # Read the content of the entire file ['Hello \ n', 'World \ n', 'Hello \ n', 'python']
>>> File. tell () # after reading, the seek location is displayed, that is, the last part of the file.
27L # Long Integer
>>> File. name # view the file name
'Test.txt'
>>> File. close () # close the file

When I first started to test the usage of read and readline, I thought it was an out-of-stack operation because I only needed to read it once and then read it later. Obviously, after I know the seek method, I know it is not. I only know that the seek position is moved back every time I read it, and each read is based on the position of the seek. Therefore, if you need to read the file content from the beginning, set the file location to start, that is, seek (0 ).

>>> Filebench open('test.txt ', 'w') >>> file. write ('\ nwelcome') # overwrite the previous content> file. writelines ('I love python') >>> file. close () # changes to the file content can be viewed only when the file is closed
>>> Filebench open('test.txt ', 'A') # append the file to the end of the file without overwriting >>> file. writelines ('this is a test') >>> file. close ()

The shutil module is sometimes required for file-related operations:

>>> Import shutil >>> shutil.copyfile('test.txt', '123.txt ') # The parameter can only be a file >>> shutil. copy ("olddir", "newfileordir") # olddir can only be a folder, newfile can be a file, or a target directory >>> shutil. copytree ("olddir", "newdir") # Both olddir and newdir can only be directories, and newdir must not exist >>> shutil. move ("oldpos", "newpos") # move a file or directory> shutil. rmtree ("dir") # Delete empty directories and directories with content> import OS
>>> OS. rmdir ("dir") # Only empty directories can be deleted> OS. remove ("file") # delete a file >>> OS. rename ("oldname", "newname") # This command is used for files or directories.

 

File encoding:

# Obtain the default encoding of the current environment >>> import sys >>> import locale >>> sys. getdefaultencoding () # returns the default character encoding 'ascii '> sys. getfilesystemencoding () # Return the encoding 'mbcs '> locale used to convert the Unicode file name to the system file name. getdefalocallocale () # obtain the default region settings and return the tuples (language, encoding) ('zh _ cn', 'cp936 ') >>> locale. getpreferredencoding () # Return the User-Defined text data encoding 'cp936'

                                                                          

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.