OS operation file and file path instance rollup in Python _python

Source: Internet
Author: User
Tags mkdir parent directory readline file permissions python script

The examples in this article describe the methods of OS operation files and file paths in Python. Share to everyone for your reference. The specific analysis is as follows:

Python get file Top level directory: Retrieve the directory of the file directory

Copy Code code as follows:
Os.path.abspath (Os.path.join (os.path.dirname (' settings.py '), Os.path.pardir)

Os.path.pardir is the parent directory, Os.path.abspath is the absolute path
For example, look at the output:
Copy Code code as follows:
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
.. #这是两个点 ".." is the representation of the parent directory
..
G:\work

Get file Current path:

Copy Code code as follows:
Os.path.dirname (Os.path.abspath (' __file__ '))


The operations in Python for files, folders (file action functions) need to involve OS modules and Shutil modules.
Get the current working directory, which is the directory path of the current Python script work: OS.GETCWD ()
Returns all file and directory names under the specified directory: Os.listdir ()
function to delete a file: Os.remove ()
Delete 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 ()
Determine whether it is an absolute path: Os.path.isabs ()
Verify that the given path is really stored: os.path.exists ()
Returns the directory name and filename of a path: Os.path.split () eg os.path.split ('/home/swaroop/byte/code/poem.txt ') results: ('/home/swaroop/byte/code ' , ' Poem.txt ')
Detach extension: Os.path.splitext ()
Get path name: Os.path.dirname ()
Get filename: Os.path.basename ()
Run shell command: Os.system ()
Reading and setting 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: Os.name for Windows, it is ' NT ', and for Linux/unix users, it's ' POSIX '
Renaming: Os.rename (old, new)
To create a multilevel directory: Os.makedirs (r "C:\python\test")
Create a single directory: Os.mkdir ("Test")
Get file properties: Os.stat (file)
Modify file permissions and timestamp: os.chmod (file)
Terminate the current process: Os.exit ()
Get File Size: os.path.getsize (filename)


Directory Operations:

Os.mkdir ("file") Create 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, NewFile can be a file, or it can be a target directory
To copy a folder:
Shutil.copytree ("Olddir", "Newdir") Olddir and Newdir can only be directories, and newdir must not exist
Renaming files (directories)
Os.rename ("Oldname", "newname") files or directories are all using this command
Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
deleting files
Os.remove ("file")
Delete Directory
Os.rmdir ("dir") can only delete empty directories
Shutil.rmtree ("dir") empty directory, content directory can be deleted
Convert Directory
Os.chdir ("path") Change path

Pyhton File Action function:

Os.mknod ("Test.txt") creates an empty file
fp = open ("Test.txt", W) opens a file directly and creates a file if it does not exist
About open mode:
W opens in write mode,
A opens in Append mode (starting with EOF, creating a new file if necessary)
R+ Open in read-write mode
w+ opens in read-write mode (see W)
A + is opened 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 and write mode (see r+)
Wb+ opens in binary read and write mode (see w+)
Ab+ opens in binary read and write mode (see A +)

Fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns to this list. In fact, its internal is through the Loop call ReadLine () to achieve. If the size argument is supplied, the size is the total length of the read content, meaning that it may be read only as part of the file.
Fp.write (str) #把str写到文件中, write () does not add a newline character after Str
Fp.writelines (seq) #把seq的内容全部写到文件中 (multiple lines of one-time write). This function is also written faithfully and does not add anything behind each line.
Fp.close () #关闭文件. Python will automatically close a file after a file is not used, but this feature is not guaranteed, it is best to develop their own habit of shutting down. If a file is turned on after it has been closed it will produce valueerror
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (in Unix systems)
Fp.tell () #返回文件操作标记的当前位置, at the beginning of the file as the origin
Fp.next () #返回下一行, and the file action tag is shifted to the next line. When you use a file for a statement such as. in file, you call the next () function to iterate through it.
Fp.seek (Offset[,whence]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file, typically a positive number. However, if the whence parameter is provided, the whence can be calculated from scratch for 0, and 1 indicates the current position is the origin calculation. 2 indicates that the origin is computed at the end of the file. Note that if the file is opened in a A or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is performed.
Fp.truncate ([size]) #把文件裁成规定的大小, the default is the location where the current file action tag is to be trimmed. If the size is larger than a file, depending on the system, you may not change the file, or you can use 0 to make up the file to the appropriate size, or you can add some random content.


Related Examples

1 Add "_fc" to all picture names under the folder
Python code:

Copy Code code as follows:
#-*-Coding:utf-8-*-
Import re
Import OS
Import time
#str. Split (string) split string
# ' connectors '. Join (list) to make lists into strings
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) #分割出目录与文件
Lists = File_path[1].split ('. ') #分割出文件与文件扩展名
File_ext = lists[-1] #取出后缀名 (list slicing operation)
Img_ext = [' bmp ', ' jpeg ', ' gif ', ' psd ', ' png ', ' jpg ']
If File_ext in Img_ext:
Os.rename (path,file_path[0]+ '/' +lists[0]+ ' _fc. ') +file_ext)
I+=1 #注意这里的i是一个陷阱
#或者
#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 () is useful for path handling

Img_dir = ' D:\\xx\\xx\\images '
Img_dir = img_dir.replace (' \ \ ', '/')
Start = Time.time ()
i = 0
Change_name (Img_dir)
c = Time.time ()-Start
Print (' program runs time consuming:%0.2f '% (c))
Print (' A total of%s pictures '% (i))


Output results:
Program Run time: 0.11
109 Photos processed in total

I hope this article will help you with your Python programming.

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.