Summary of OS operation files and file path instances in python

  • 2020-04-02 14:28:20
  • OfStack

This article illustrates how OS operates on files and file paths in python. Share with you for your reference. Specific analysis is as follows:

Python gets the directory above the file: takes the directory above the directory where the file is located


Os.path.pardir is the parent directory and os.path.abspath is the absolute path
For example, take a look at the output:
print os.path.dirname(os.path.abspath("__file__"))
print os.path.pardir
print os.path.join(os.path.dirname("__file__"),os.path.pardir)
print os.path.abspath(os.path.join(os.path.dirname("__file__"),os.path.pardir))

Output results:

  G: \ work \ python
  .                                           This is the two points ".." , which is the representation of the parent directory
  G: \ work
Get the current path of the file:


Operations on files, folders (file manipulation functions) in python need to involve the OS module and the shutil module.
Get the current working directory, which is the directory path where the current Python script works: os.getcwd()
Returns all files and directory names in the specified directory :os.listdir()
The os.remove() function deletes a file :os.remove()
Remove multiple directories: os.removedirs (r "c: \python")
Verify that the given path is a file: os.path.isfile()
Verify that the given path is a directory: os.path.isdir()
Os.path. Isabs ()
Verify that the given path exists :os.path. Exists ()
Returns a path to the directory name and file name: OS. Path. The split () eg OS. The path. The split ('/home/swaroop/byte/code/poem TXT ') results: '/ home/swaroop/byte code', 'poem. TXT)
Split extension: os.path.splitext()
Get path name: os.path.dirname()
Get file name: os.path.basename()
Run the shell command: os.system()
Read and set environment variables :os.getenv() and os.putenv()
Gives the line terminator used by the current platform :os.linesep Windows USES '\r\n', Linux USES '\n' and Mac USES '\r'
Indicates the platform you are using: is 'nt' for Windows and 'posix' for Linux/Unix users
Rename: os.rename (old, new)
Create multilevel directory: os.makedirs (r "c: \python\test")
Create a single directory: os.mkdir (" test ")
Get file properties: os.stat (file)
Modify file permissions with timestamp: os.chmod (file)
Terminate the current process: os.exit ()
Get file size: os.path.getsize (filename)
Directory operation:

Os.mkdir ("file") creates a directory
Copy files:
Shutil. Copyfile ("oldfile","newfile") oldfile and newfile can only be files
Shutil. Copy ("oldfile","newfile") oldfile can only be a folder, and 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 files (directories)
Os.rename ("oldname","newname") files or directories use this command
Moving files (directories)
Shutil. Move (" oldpos ", "newpos")
Delete the file
OS. Remove (" file ")
Delete the directory
Os.rmdir ("dir") can only remove empty directories
Shutil. Rmtree ("dir") empty directory, the directory with content can be deleted
Conversion directory
OS. The chdir (" path ") in path

Pyhton file operation function:

Os.mknod ("test.txt") creates an empty file
Fp = open("test.txt",w) directly opens a file and creates a file if the file does not exist
About the open mode:
W opens as a write,
A opens in append mode (starting with EOF and creating new files if necessary)
R + opens in read/write mode
W + opens in read/write mode (see w)
A + opens in read/write mode (see a)
Rb opens in binary read mode
Wb opens in binary write mode (see w)
Ab opens in binary append mode (see a)
Rb + opens in binary read/write mode (see r+)
Wb + opens in binary read/write mode (see w+)
Ab + opens in binary read/write mode (see a+)
Fp. Read ([size]) #size is the length read in byte
Fp.readline ([size]) # reads a line. If size is defined, it is possible to return only a portion of the line
Fp.readlines ([size]) # takes each line of the file as a member of a list and returns the list. It's actually done internally by looping through readline(). If you supply the size parameter, size is the total length of the read, which means that you may read only a portion of the file.
Fp. Write (STR) # writes STR to a file. Write () does not add a new line after STR
Fp.writelines (seq) # writes seq in its entirety to a file (multiple lines written at once). This function also just writes faithfully, not adding anything after each line.
Fp.close () # closes the file. Python automatically closes a file when it's not in use, but that's not guaranteed, and it's best to get into the habit of doing it yourself. A ValueError occurs if a file is manipulated after closing
Fp.flush () # writes the contents of the buffer to the hard disk
Fp. Fileno () # returns a long integer "file tag"
Fp.isatty () # file isa terminal device file (in Unix systems)
Fp.tell () # returns the current location of the file action tag, starting at the beginning of the file () # returns the next line and moves the file action tag to the next line. Use a file for... Statements such as in file are traversed by calling the next() function.
Fp. Seek (offset, whence []) # will play operation signature file moved to the location of the offset. This offset is usually calculated relative to the beginning of the file and is usually positive. But if provides whence parameter is not necessarily, whence may be computed on the basis of 0 said from the beginning, 1 origin calculation for the current position. 2 means to calculate with the end of the file as the origin. Note that if the file is opened in a or a+ mode, the file action flag is automatically returned to the end of the file each time a write is made.
Fp.truncate ([size]) # truncate the file to the specified size, by default, to the location of the current file action tag. If the size is larger than the size of the file, it may not change the file according to the system, it may fill the file to the corresponding size with 0, or it may add some random contents.
Relevant example

1 add '_fc' to all images in the folder
Python code:

# -*- coding:utf-8 -*-
import re
import os
import time
#str.split(string) Split string
#' connector '.join(list) Group the list into a string
def change_name(path):
global i
if not os.path.isdir(path) and not os.path.isfile(path):
return False
if os.path.isfile(path):
file_path = os.path.split(path) # Separate directories and files
lists = file_path[1].split('.') # Split the file with the file extension
file_ext = lists[-1] # Take the suffix name ( List slice operation )
img_ext = ['bmp','jpeg','gif','psd','png','jpg']
if file_ext in img_ext:
i+=1 # Notice the i It's a trap
# or
#img_ext = 'bmp|jpeg|gif|psd|png|jpg'
#if file_ext in img_ext:
# print('ok---'+file_ext)
elif os.path.isdir(path):
for x in os.listdir(path):
change_name(os.path.join(path,x)) #os.path.join() It's useful for path processing img_dir = 'D:\xx\xx\images'
img_dir = img_dir.replace('\','/')
start = time.time()
i = 0
c = time.time() - start
print(' Program running time :%0.2f'%(c))
print(' In total %s image '%(i))

Output results:
Program running time :0.11
In all, 109 images were processed

I hope this article has helped you with your Python programming.

Related articles: