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 (path)

function to delete a file:os.remove (file)

Delete multiple directories:os.removedirs (r "C:\python") # R indicates that the string is not escaped

Verify that the given path is a file:os.path.isfile (r "c:\python\hello.py")--- True

Verify that the given path is a directory:os.path.isdir (r "C:\python")--- True

Determine if it is a linked file:Os.path.islink (r "c:\python\hello.py")--- False

Determine if absolute path:os.path.isabs (r ". \python\")--- False

Determine if a file or path exists:os.path.exists (r "c:\python\hello.py")--- True

Detach file Name: os.path.split (r "c:\python\hello.py") --("C:\\python", "hello.py")

Detach extension:Os.path.splitext (r "c:\python\hello.py") --("C:\\python\\hello", ". Py")

Get path name:os.path.dirname (r "c:\python\hello.py")-- "C:\\python"

Get Superior Absolute path:Os.path.abspath (Os.path.join (Os.path.dirname (sys.argv[0]), Os.path.pardir))

Get filename:os.path.basename (r "r:\python\hello.py")-- "hello.py"

Get file name without suffix:os.path.splitext (Os.path.basename ("/a/b/c.txt")) [0] --"C"

Run operating system or 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)

Executing in the background:OS.SPAWNV ()

Open a file by using the Use open method

Open (name[, mode[, Buffering])

Mode has the following modes,

R opens the file in read mode to read the file information.

W writes the file to write information to the file. If the file exists, empty the file, and then write the new content

A opens the file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file), and if the file does not exist, create

r+ Open the file as read-write, read and write the file.

w+ removes the file contents and then opens the file as read-write.

A + opens the file in read-write mode and moves the file pointer to the end of the file.

b binary mode, must be used in conjunction with "RB", "WB", "AB" mode, can not be used alone, processing binary files need to use the sub-mode, such as sound, pictures and so on.

There is also a "+" for reading and writing mode, must be in line with "r+", "w+", "A +", "rb+", "wb+", "ab+" use, you can not use the mode alone.

The default value for mode is "R" read mode.

File operation:

Os.mknod ("test.txt") Create an empty file
fp = open ("Test.txt", W) opens a file directly and creates a file if the file does not exist

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")Create a Directory
To copy a 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
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")The file or directory is used by this command
Moving Files (directories)
shutil.move ("Oldpos", "Newpos")
deleting files
os.remove ("file")
Delete Directory
os.rmdir ("dir")Only empty directories can be deleted
shutil.rmtree ("dir")Empty directories, contents of the directory can be deleted
Converting catalogs
os.chdir ("path")Change path

Traverse Folder

Os.walk ("dir")

Os.listdir ("dir")

More functions can use Help (OS) or dir (OS) to see its usage

Here is a piece of broken code

#coding =utf-8

Import OS

Import Shutil

Dir_path= "/var/log/"

If not os.path.exists (Dir_path):

Os.mkdir (Dir_path)

Os.makedirs (Dir_path) # Create a multilevel folder

file_name = "Test.log"

Content = "Body"

f = File (Os.path.join (Dir_path, file_name), "W")

F.write (Content.encode ("gb2312"))

F.close ()

# Whether it is a file

If Os.path.isfile (Os.path.join (Dir_path, file_name)):

Os.remove (Os.path.join (Dir_path, file_name))

# Copy files

Old_file = "/var/log/test.log"

New_file = "/var/log/test.log.bak"

Shutil.copyfile (Old_file, New_file)

Get folder Size

Import OS

def getdirsize (dir):

"" Returns the folder Size "" "

Size = 0L

For root, dirs, files in Os.walk (dir):

Size + = SUM ([Os.path.getsize (Os.path.join (root, name)) for name in Files])

return size

def sizeof_fmt (num):

"" is formatted as readable "" "

For x in [' bytes ', ' KB ', ' MB ', ' GB ']:

If num < 1024.0 and num >-1024.0:

Return "%3.1f%s"% (num, x)

Num/= 1024.0

Return "%3.1f%s"% (num, ' TB ')

if __name__ = = ' __main__ ':

FileSize = Getdirsize (R ' C:\Windows ')

Print FileSize

Print sizeof_fmt (filesize)

Document content Source:

Http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html

http://wiki.woodpecker.org.cn/moin/pyabsolutelyzipmanual#open.2bac9lh072zm1pxa-

The use of With

Python 2.6 has been added with the use of, with can be stable and reliable operation of the file

There are some tasks that may need to be set up beforehand to do cleanup work afterwards. For this scenario, Python's with statement provides a very convenient way to handle it. A good example is file handling, where you need to get a file handle, read the data from the file, and then close the file handle.

2.5 Before this is the operation of the file

File = Open ("/tmp/foo.txt")

Try

data = File.read ()

Finally

File.close ()

Although this code works well, it's too verbose. This is the time for a show with a skill. In addition to having a more elegant syntax, with can also handle the exception generated by the context environment very well. The following is the code with the version:

With open ("/tmp/foo.txt") as File:

data = File.read ()

How does the with work?

It looks magical, but not just magic, and Python's handling of with is smart. The basic idea is that the object with which the value is evaluated must have a __enter__ () method, a __exit__ () method.

Immediately after the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS. The __exit__ () method of the previous return object is called when all code blocks following the with are executed.

The following example can specify how with works:

#!/usr/bin/env python

# with_example01.py

Class Sample:

def __enter__ (self):

Print "in __enter__ ()"

Return "Foo"

def __exit__ (self, type, value, trace):

Print "in __exit__ ()"

Def get_sample ():

Return Sample ()

With Get_sample () as Sample:

Print "Sample:", sample

Run the code, output as follows

bash-3.2$./with_example01.py

In __enter__ ()

Sample:foo

In __exit__ ()

Summarize:

The Python with statement provides an effective mechanism for making the code more concise and easier to clean up when the exception is generated.

With the content reference:

http://python.42qu.com/11155501

http://sdqali.in/blog/2012/07/09/understanding-pythons-with/

Python file operations

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.