Python,os operation file, file path (previous level directory) __python

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

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

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:

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: 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:

#-*-Coding:utf-8-*-
Import re
import OS
Import time
#str. Split (String) split string
# ' connectors '. Join (list) Make a list of strings
Def change_name (path):
Global I
If not os.path.isdir (path) to Os.path.isfile (path):
Return False
If Os.path.isfile (path):
File_path = os.path.split (path) #分割出目录与文件
Lists = File_path[1].split ('. ') # Split out file and file extension
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 ( path,x) #os. Path.join () is useful for path processing


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

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.