Python file operation instance

Source: Internet
Author: User
Tags posix
Python file operation instance Source: EDIT: EXP
Time: 2012-09-14

[Python]
#-*-Coding: UTF-8 -*-
 
Import OS
Import shutil
 
#1. Path operations: Judgment, acquisition, and deletion
 
#1. Get the current working directory, that is, the directory path for the current Python script to work: OS. getcwd ()
# Print: currentpath: F:/learnpython
Currentpath = OS. getcwd ()
Print "currentpath:", currentpath
#2. Return all files and directory names in the specified directory: OS. listdir ()
# Print: OS. listdir (): 'test.txt ', 'testrw. PY ', 'test1.txt', 'cmd. py', 'rwfile. py', 'downloadfile. py', 'date. py', 'time. py', 'datetime. py', 'file. py']
Print "OS. listdir ():", OS. listdir ('f:/learnpython ')
 
Path = "F:/Mmmmmmm/debug_taobao_200003@taobao_android1.6_3.2.1.apk"
#3. Determine whether the given path is actually stored: OS. Path. exists ()
If OS. Path. exists (PATH ):
# Delete an object: OS. Remove ()
OS. Remove (PATH)
Else:
Print path, "not exist"
 
#4. Delete multiple directories: OS. removedirs ("C:/Python ")
# It can only delete empty directories. If there is content in the directory, it will not be deleted.
If OS. Path. exists ("D:/woqu "):
OS. removedirs ("D:/woqu ")
Else:
OS. mkdir ("D:/woqu ")
OS. removedirs ("D:/woqu ")
 
#5. Determine whether the given path is a file: OS. Path. isfile ()
# Print: True
Print OS. Path. isfile ("D:/Hello/json.txt ")
#6. Determine whether the given path is a directory: OS. Path. isdir ()
# Print: True
Print OS. Path. isdir ("D:/Hello ")
#7. Determine whether the path is absolute: OS. Path. isabs ()
# Print: True
Print OS. Path. isabs ("D:/Hello ")
# Determine if it is a link
Print OS. Path. islink ('HTTP: // www.baidu.com ')
#8. Return the directory name and file name of a path: OS. Path. Split ()
# Eg OS. Path. Split ('/home/swaroop/byte/code/poem.txt') Result: ('/home/swaroop/byte/Code', 'poem.txt ')
# Print: ('d: // Hello ', 'json.txt ')
Print OS. Path. Split ("D:/Hello/json.txt ")
#9. Separation Extension: OS. Path. splitext ()
# Print :( 'd: // Hello // json', '.txt ')
Print OS. Path. splitext ("D:/Hello/json.txt ")
#10. Obtain the path: OS. Path. dirname ()
# Print: 'd: // Hello'
Print OS. Path. dirname ("D:/Hello/json.txt ")
#11. Get the file name: OS. Path. basename ()
# Print: 'json.txt'
Print OS. Path. basename ("D:/Hello/json.txt ")
 
 
#13. indicates the platform you are using: OS. Name for Windows, it is 'nt ', and for Linux/Unix users, it is 'posix'
Print "OS. Name:", OS. Name
 
#14. LinEx commands
If OS. Name = 'posix ':
# Read and set environment variables: OS. getenv () and OS. putenv ()
Home_path = OS. Environ ['home']
Home_path = OS. getenv ('home') # Read Environment Variables
Elif OS. Name = 'nt ':
Home_path = 'd :'
Print 'home _ path: ', home_path
 
#15. line terminator used by the current platform: OS. linesep: '/R/N' for Windows,'/N' for Linux, and '/R' for Mac'
Print (OS. linesep)
 
#16. The paths for Windows and Linux are a little different. Windows is separated by //, while Linux is separated,
# The OS. SEP will automatically select which separator to use based on the system.
Print (OS. SEP)
 
#17. Rename: OS. Rename (old, new)
# First go to the directory
OS. chdir ("D: // hello ")
Print OS. getcwd ()
#18. Rename again
OS. Rename ("1.txt"," 11.txt ")
#19. Create a multilevel Directory: OS. makedirs ("C:/Python/test ")
OS. makedirs ('d:/h/e/l/L/o ')
#20. Create a single directory: OS. mkdir ("test ")
OS. mkdir ('d:/F ')
#21. Get file attributes: OS. Stat (file)
# Print: NT. stat_result (st_mode = 33206, st_ino = 0l, st_dev = 0, st_nlink = 0, st_uid = 0, st_gid = 0, st_size = 497l, st_atime = 1346688000l, st_mtime = hour, st_ctime = 1346748052l)
Print OS. Stat ('d:/Hello/json.txt ')
#22. Modify the File Permission and timestamp: OS. chmod (path, Mode)
# Here are the introduction: http://blog.csdn.net/wirelessqa/article/details/7974477
#23. Terminate the current process: OS. Exit ()
#24. Get file size: OS. Path. getsize (filename)
Print OS. Path. getsize ('d:/Hello/json.txt ')

File Operations:
OS. mknod ("test.txt") to create an empty file
Fp = open ("test.txt", W) open a file directly. If the file does not exist, create a file.

About open mode:

W open in write mode,
A is opened in append mode (starting from EOF and creating a file if necessary)
R + Enabled in read/write mode
W + is enabled in read/write mode (see W)
A + is enabled in read/write mode (see)
RB is enabled in binary read mode.
WB is enabled in binary write mode (see W)
AB is enabled in binary append mode (see)
RB + is enabled in binary read/write mode (see R +)
WB + is enabled in binary read/write mode (see w +)
AB + is enabled in binary read/write mode (see A +)

 

FP. Read ([size]) # size indicates the read length, in bytes.

FP. Readline ([size]) # Read a row. If the size is defined, only one part of the row may be returned.

FP. readlines ([size]) # 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.

FP. Write (STR) # Write STR to the file. Write () does not add a linefeed after Str.

FP. writelines (SEQ) # Write All seq content to a file (multiple rows are written at one time ). This function is only faithfully written without adding anything to the end of each line.

FP. Close () # close the file. Python will automatically close the file after a file is not used, but this function is not guaranteed, it is best to develop your own habit of closing. If a file is closed and operated on it, valueerror is generated.

FP. Flush () # Write the buffer content to the hard disk

FP. fileno () # returns a long integer "file tag"

FP. isatty () # Whether the file is a terminal device file (in UNIX)

FP. Tell () # Return the current position of the file operation mark, starting with the file as the origin

FP. Next () # return the next line and move the operation mark of the file to the next line. Use a file... When a statement such as in file is called, the next () function is called to implement traversal.

FP. Seek (offset [, whence]) # mark the file operation and move it to the offset position. This offset is generally calculated relative to the beginning of the file, and is generally a positive number. However, if the whence parameter is provided, it is not necessary. If the whence parameter is 0, it indicates that the calculation starts from the beginning, and 1 indicates that the calculation is based on the current position. 2 indicates that the origin is the end of the file. Note that if the file is opened in a or a + mode, the file operation mark is automatically returned to the end of the file during each write operation.

FP. truncate ([size]) # crop the file to the 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.

 

Directory operation:
OS. mkdir ("file") to create a directory
Copy a file:
Shutil. copyfile ("oldfile", "newfile") both oldfile and newfile can only be files.
Shutil. Copy ("oldfile", "newfile") oldfile can only be a folder. newfile can be a file or a target directory.
Copy Folder:
Shutil. copytree ("olddir", "newdir") both olddir and newdir can only be directories, and newdir must not exist
Rename a file (directory)
OS. Rename ("oldname", "newname") files or directories all use this command
Move a file (directory)
Shutil. Move ("oldpos", "newpos ")
Delete an object
OS. Remove ("file ")
Delete directory
OS. rmdir ("dir") can only delete empty directories
Shutil. rmtree ("dir") empty directories and directories with content can be deleted.
Conversion directory
OS. chdir ("path") change path

Instance: Add '_ once-ler' to the names of all images in the folder'

[Python]
#-*-Coding: UTF-8 -*-
Import re
Import OS
Import time
# Str. Split (string) Split string
# 'Connector '. Join (list) combines the list into a string
 
Def file_changename (filepath ):
Global picnum
File_path = OS. Path. Split (filepath) # split the Directory and file
Lists = file_path [1]. Split ('.') # split the file and file extension
File_ext = lists [-1] # retrieve the suffix (list slicing operation)
Img_ext = ['bmp ', 'jpeg', 'gif', 'psd ', 'png', 'jpg ']
If file_ext in img_ext:
OS. Rename (filepath, file_path [0] + '/' + lists [0] + '_ Once-ler.' + file_ext)
Picnum + = 1
 
 
Def change_name (PATH ):
If not OS. Path. isdir (PATH) and not OS. Path. isfile (PATH ):
Return false
Elif OS. Path. isfile (PATH ):
File_changename (PATH)
Elif OS. Path. isdir (PATH ):
For X in OS. listdir (PATH ):
Print 'OS. Path. Join (path, X):', OS. Path. Join (path, X)
File_changename (OS. Path. Join (path, x ))
# OS. Path. Join () is useful in path processing.
If _ name _ = '_ main __':
Img_dir = 'd: // Hello // capture'
Print img_dir
Img_dir = img_dir.replace ('//','/')
Print img_dir
Start = Time. Time ()
Print start
Picnum = 0
Change_name (img_dir)
Spenttime = Time. Time ()-start
Print ('runtime: % 0.2f '% (spenttime ))
Print ('% s images processed in total '% (picnum ))

The following file is running incorrectly, from: http://rsjy.org/2023.html
[Python]
#! /Usr/bin/Python
#-*-Coding: UTF-8 -*-
Import OS
# Define several functions
Def del_file (wpath ):
OS. Remove (wpath) # delete an object
Def del_dir (wpath ):
OS. removedirs (wpath) # delete an empty folder
Def gen_dir (wpath ):
If OS. Path. exists (wpath ):
Pass
Else:
OS. mkdir (wpath) # create a folder
Def gen_file (wpath ):
If OS. Path. exists (wpath ):
Pass
Else:
OS. mknod (wpath) # create a file
 
Print (OS. SEP)
Print (OS. linesep) # string indicates the row Terminator used by the current platform
 
# Print (OS. Environ)
If OS. Name = 'posix ':
Home_path = OS. Environ ['home']
Home_path = OS. getenv ('home') # Read Environment Variables
Elif OS. Name = 'nt ':
Home_path = 'd: '# not tested in win
 
# Define the name of the folder and file for testing
Tep_dir = 'xx _ tep'
Tep_dir_a = 'tep _ dir_a'
Tep_dir_ B = 'tep _ dir_ B'
Tep_file_a = 'tep_file_a.txt'
Tep_file_ B = 'tep _ file_ B .py'
Tep_file_c = 'tep _ file_c.c'
# The full path of the merged folder and file
Path_tep = OS. Path. Join (home_path, tep_dir)
Path_dir_a = OS. Path. Join (path_tep, tep_dir_a)
Path_dir_ B = OS. Path. Join (path_tep, tep_dir_ B)
Path_file_a = OS. Path. Join (path_dir_a, tep_file_a)
Path_file_ B = OS. Path. Join (path_dir_a, tep_file_ B)
Path_file_c = OS. Path. Join (path_dir_ B, tep_file_c)
# Generate corresponding folders and files in the system
Gen_dir (path_tep)
Gen_dir (path_dir_a)
Gen_dir (path_dir_ B)
Gen_file (path_file_a)
Gen_file (path_file_ B)
Gen_file (path_file_c)
 
CWD = OS. getcwd () # obtain the current working directory, that is, the directory path of the current Python script.
Wlist = OS. listdir (CWD)
For WLI in wlist:
Print (WLI)
OS. chdir (path_tep) # Switch path
CWD = OS. getcwd () # obtain the current working directory, that is, the directory path of the current Python script.
Wlist = OS. listdir (CWD)
For WLI in wlist:
Print (WLI)
 
If OS. Path. isdir (path_dir_a): # Check whether the folder is used
Tep_size = OS. Path. getsize (path_dir_a)
Print (tep_size)
 
If OS. Path. isfile (path_file_a ):
Tep_size = OS. Path. getsize (path_file_a) # obtain the file size
Print (tep_size)
 
For wroot, wdirs, wfiles iN OS. Walk (path_tep ):
For wfile in wfiles:
File_path = OS. Path. abspath (wfile) # obtain the absolute path
Print (file_path)
 
# Returned file name
Filename = OS. Path. basename (path_file_a)
Print (filename)
 
# Returned file path
Dirname = OS. Path. dirname (path_file_a)
Print (dirname)
 
# Splitting file names and directories
# In fact, if you fully use a directory, it will also separate the last directory as a file name,
# At the same time, it does not determine whether a file or directory exists
(Filepath, filename) = OS. Path. Split (path_file_a)
Print (filepath, filename)
(Fname, fext) = OS. Path. splitext (filename) # separated file names and extensions
Print (fname, fext)
# Clear files and folders
Del_file (path_file_a)
Del_file (path_file_ B)
Del_dir (path_dir_a)
Del_file (path_file_c)
Del_dir (path_dir_ B)

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.