About Python file operations

Source: Internet
Author: User

files, folders in Python (file manipulation function) operation requires an OS module and a shutil module.

Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()

Returns all files and directory names under the specified directory name:os.listdir ()

function to delete a file:os.remove ()

Delete multiple directories:os.removedirs (r "C:\python")

Verifies whether the given path is a file:os.path.isfile ()

Verify that the given path is a directory:os.path.isdir ()

Determine if it is an absolute path:os.path.isabs ()

Verify that the given path is really saved:os.path.exists ()

Returns 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 ')

Detach extension:os.path.splitext ()

Get path name:os.path.dirname ()

Get file name:os.path.basename ()

Run 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:os.name for Windows, it is ' NT ', and for Linux/unix users, it is ' POSIX '

Rename:os.rename (old, new)

Create a multilevel directory:os.makedirs (r "C:\python\test")

Create a single directory:os.mkdir ("test")

Get file attributes:os.stat (file)

Modify file permissions and timestamps:os.chmod (file)

Terminate current process:os.exit ()

Get file Size:os.path.getsize (filename)

file operation: 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 open mode:

W opens in write mode, a opens in append (starting with EOF, creates a new file if necessary) r+ open in read-write mode w+ open in read-write mode (see W) A + opens in read/write mode (see a) RB is read in binary Mode open WB opens in binary write mode (see W) AB opens in binary append mode (see a) rb+ in binary read-write mode (see r+) wb+ open in binary read-write mode (see w+) ab+ with binary read Write mode open (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 the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.

fp.write (str) #把str写到文件中, write () does not add a newline character after Str

fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.

fp.close () #关闭文件.  Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates VALUEERROR

Fp.flush () #把缓冲区的内容写入硬盘

Fp.fileno () #返回一个长整型的 "file label"

Fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)

Fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file

fp.next () #返回下一行 and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.

Fp.seek (offset[,whence]) #将文件打操作标记移到offset的位置. 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, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made.

fp.truncate ([size]) #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.

Directory Operations:os.mkdir ("file")To create a directory copy file:shutil.copyfile ("Oldfile", "NewFile")Oldfile and NewFile can only be files.shutil.copy ("Oldfile", "NewFile")Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory Replication folder:shutil.copytree ("Olddir", "Newdir")Olddir and Newdir can only be directories, and Newdir must not have a renamed file (directory)os.rename ("Oldname", "NewName")Files or directories are used to move files (directories) using this commandshutil.move ("Oldpos", "Newpos")deleting filesos.remove ("file")Delete Directoryos.rmdir ("dir")Only empty directories can be deletedshutil.rmtree ("dir")Empty directory, content directory can be deleted from the conversion directoryos.chdir ("path")Change path

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  # ' connector '. Join ( List) make 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)   #分割出目录与文件          lists = File_path[1].split ('. ')   #分割出文件与文件扩展名          file_ext = lists[-1]  #取出后缀名 (list slicing operations)           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 in 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 Runtime:%0.2f '% (c)) print (' Processed%s picture '% (i))

Output Result:

Program run time: 0.11 total 109 pictures processed

About Python file operations

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.