Python operation file Some examples summary

Source: Internet
Author: User
Tags glob mkdir readline file permissions in python

The operations in Python for files, folders (file action functions) need to involve OS modules and Shutil modules.

Import OS required before operation;

Returns the current directory, excluding the filename: OS.GETCWD ();

Returns all files and directory names under the specified directory: Os.listdir ("dirname");

Os.mknod ("Test.txt") to create an empty file, failed to test successfully, error OSError: [Errno 1] Operation not permitted, have not checked the cause, with another method to achieve Os.system ("touch Test.txt ");

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 ' RN ', 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:pythontest")

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)


File actions:
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 (empty the original content),
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.

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


Cases


1. FileHandle = open (' Test.txt ', ' W ')

FileHandle = open (' Test.txt ', ' W ')

' W ' means that the file will be written to the data and the other parts of the statement are well understood. The next step is to write the data to the file:

1. Filehandle.write (' This are a test.nreally, it is. ')

Filehandle.write (' This are a test.nreally, it is. ')

This statement will "this is a test." Write the first line of the file, "really, it is." Writes the second line of the file. Finally, we need to do cleanup work and close the file:

1. Filehandle.close ()

Filehandle.close ()

As you can see, this is really very simple under the object-oriented mechanism of Python. It is important to note that when you use the "W" method to write the data in the file again, all the original content will be deleted. If you want to keep the original content, you can use the "a" method to end the file with additional data:

1. FileHandle = open (' Test.txt ', ' a ')
2. Filehandle.write (' nnbottom line. ')
3. Filehandle.close ()

FileHandle = open (' Test.txt ', ' a ')
Filehandle.write (' nnbottom line. ')
Filehandle.close ()

We then read the Test.txt and display the contents:

1. FileHandle = open (' Test.txt ')
2. Print Filehandle.read ()
3. Filehandle.close ()

FileHandle = open (' Test.txt ')
Print Filehandle.read ()
Filehandle.close ()

The above statement reads the entire file and displays the data in it. We can also read a line in the file:

1. FileHandle = open (' Test.txt ')
2. Print filehandle.readline () # "This is a test."
3. Filehandle.close ()

FileHandle = open (' Test.txt ')
Print filehandle.readline () # "This is a test."
Filehandle.close ()


You can also save the contents of a file to a list:

1. FileHandle = open (' Test.txt ')
2. FileList = Filehandle.readlines () <div></div>
3. For fileline in FileList:
4. print ' >> ', fileline
5. Filehandle.close ()

FileHandle = open (' Test.txt ')
FileList = Filehandle.readlines ()
For Fileline in FileList:
print ' >> ', fileline
Filehandle.close ()

When Python reads a file, it remembers its location in the file, as follows:

1. FileHandle = open (' Test.txt ')
2. Garbage = Filehandle.readline ()
3. Filehandle.readline () # "Really, it is." Filehandle.close ()

FileHandle = open (' Test.txt ')
garbage = Filehandle.readline ()
Filehandle.readline () # "Really, it is." Filehandle.close ()

As you can see, only the second line shows up. However, we can get Python to read from the beginning to solve this problem:

1. FileHandle = open (' Test.txt ')
2. Garbage = Filehandle.readline ()
3. Filehandle.seek (0)
4. Print filehandle.readline () # "This is a test."
5. Filehandle.close ()

FileHandle = open (' Test.txt ')
garbage = Filehandle.readline ()
Filehandle.seek (0)
Print filehandle.readline () # "This is a test."
Filehandle.close ()

In the example above, we let Python read the data from the first byte of the file. So the first line of text is displayed. Of course, we can also get Python's location in the file:

1. FileHandle = open (' Test.txt ')
2. Print filehandle.readline () # "This is a test."
3. Print Filehandle.tell () # "17"
4. Print filehandle.readline () # "Really, it is."

FileHandle = open (' Test.txt ')
Print filehandle.readline () # "This is a test."
Print Filehandle.tell () # "17"
Print filehandle.readline () # "Really, it is."

Or read a few bytes of content at a time in a file:

1. FileHandle = open (' Test.txt ')
2. Print Filehandle.read (1) # "T"
3. Filehandle.seek (4)
4. Print Filehandle.read (1) # "" (Original error)

FileHandle = open (' Test.txt ')
Print Filehandle.read (1) # "T"
Filehandle.seek (4)
Print Filehandle.read (1) # "" (Original error)

In Windows and Macintosh environments, you may sometimes need to read and write files in binary form, such as pictures and executables. At this point, just add a "B" to the way the file is opened:

1. FileHandle = open (' TestBinary.txt ', ' WB ')
2. Filehandle.write (' There is no spoon. ')
3. Filehandle.close ()

FileHandle = open (' TestBinary.txt ', ' WB ')
Filehandle.write (' There is no spoon. ')
Filehandle.close ()

1. FileHandle = open (' TestBinary.txt ', ' RB ')
2. Print Filehandle.read ()
3. Filehandle.close ()

FileHandle = open (' TestBinary.txt ', ' RB ')
Print Filehandle.read ()
Filehandle.close ()

Ii. obtaining information from existing documents
Using the modules in Python, you can get information from existing files. Use the OS module and the stat module to get basic information about the file:

1. Import OS
2. Import Stat
3. Import time<div></div>
4.
5. Filestats = Os.stat (' test.txt ')
6. FileInfo = {
7. ' Size ': filestats [Stat. St_size],
8. ' LastModified ': Time.ctime (filestats [Stat. St_mtime]),
9. ' LastAccessed ': Time.ctime (filestats [Stat. St_atime]),
' CreationTime ': Time.ctime (filestats [Stat. St_ctime]),
One. ' Mode ': filestats [Stat. St_mode]
12.}
13.
For Infofield, Infovalue in FileInfo:
Print Infofield, ': ' + infovalue
If Stat. S_isdir (filestats [Stat. St_mode]):
print ' Directory. '
. else:
print ' Non-directory. '

Import OS
Import Stat
Import time

Filestats = Os.stat (' test.txt ')
FileInfo = {
' Size ': filestats [Stat. St_size],
' LastModified ': Time.ctime (filestats [Stat. St_mtime]),
' LastAccessed ': Time.ctime (filestats [Stat. St_atime]),
' CreationTime ': Time.ctime (filestats [Stat. St_ctime]),
' Mode ': filestats [Stat. St_mode]
}

For Infofield, Infovalue in FileInfo:
Print Infofield, ': ' + infovalue
If Stat. S_isdir (filestats [Stat. St_mode]):
print ' Directory. '
Else
print ' Non-directory. '

The above example creates a dictionary that contains the basic information about the file. It then displays the relevant information and tells us whether the directory is open. We can also try to see if there are several other types of open:

1. Import OS
2. Import Stat
3.
4. Filestats = Os.stat (' test.txt ')
5. FileMode = filestats [Stat. St_mode]
6. If Stat. S_isreg (filestats [Stat. St_mode]):
7. print ' Regular file. '
8. Elif Stat. S_isdir (filestats [Stat. St_mode]):
9. print ' Directory. '
Elif Stat. S_islnk (filestats [Stat. St_mode]):
print ' shortcut. '
Elif Stat. S_issock (filestats [Stat. St_mode]):
print ' Socket. '
Elif Stat. S_isfifo (filestats [Stat. St_mode]):
print ' Named pipe. '
Elif Stat. S_ISBLK (filestats [Stat. St_mode]):
print ' Block special device. '
Elif Stat. S_ISCHR (filestats [Stat. St_mode]):
print ' Character special device. '

Import OS
Import Stat

Filestats = Os.stat (' test.txt ')
FileMode = filestats [Stat. St_mode]
If Stat. S_isreg (filestats [Stat. St_mode]):
print ' Regular file. '
Elif Stat. S_isdir (filestats [Stat. St_mode]):
print ' Directory. '
Elif Stat. S_islnk (filestats [Stat. St_mode]):
print ' shortcut. '
Elif Stat. S_issock (filestats [Stat. St_mode]):
print ' Socket. '
Elif Stat. S_isfifo (filestats [Stat. St_mode]):
print ' Named pipe. '
Elif Stat. S_ISBLK (filestats [Stat. St_mode]):
print ' Block special device. '
Elif Stat. S_ISCHR (filestats [Stat. St_mode]):
print ' Character special device. '

In addition, we can use "Os.path" to get basic information:

1. Import Os.path
2.
3. Filestats = ' Test.txt '
4. If Os.path.isdir (filestats):
5. print ' Directory. '
6. Elif Os.path.isfile (filestats):
7. print ' File. '
8. Elif Os.path.islink (filestats):
9. print ' Shortcut. '
Elif Os.path.ismount (filestats):
print ' Mount point. '

Import Os.path

Filestats = ' Test.txt '
If Os.path.isdir (filestats):
print ' Directory. '
Elif Os.path.isfile (filestats):
print ' File. '
Elif Os.path.islink (filestats):
print ' shortcut. '
Elif Os.path.ismount (filestats):
print ' Mount point. '

Iii. Table of Contents
As with normal files, the operation of the directory is easy to master. First, list the contents of a directory:

1. Import OS
2.
3. For fileName in Os.listdir ('/'):
4. Print FileName

Import OS

For FileName in Os.listdir ('/'):
Print FileName

As you can see, this is simple, with three lines of code to complete.
Creating a directory is also simple:

1. Import OS
2.
3. Os.mkdir (' testdirectory ')

Import OS

Os.mkdir (' testdirectory ')

Delete the directory you just created:

1. Import OS
2.
3. Os.rmdir (' testdirectory)

Import OS

Os.rmdir (' testdirectory)

Well, you can create multilevel catalogs:

1. Import OS
2.
3. Os.makedirs (' i/will/show/you/how/deep/the/rabbit/hole/goes ')

Import OS

Os.makedirs (' i/will/show/you/how/deep/the/rabbit/hole/goes ')

If you don't add anything to the folder you created, you can delete all of them at once (that is, delete all the empty folders listed):

1. Import OS
2.
3. Os.removedirs (' i/will/show/you/how/deep/the/rabbit/hole/goes ')

Import OS

Os.removedirs (' i/will/show/you/how/deep/the/rabbit/hole/goes ')

When you need to operate on a particular file type, we can select the "Fnmatch" module. The following is the contents of the ". txt" file and the file name of the ". exe" FILE:

1. Import Fnmatch
2. Import OS
3.
4. For fileName in Os.listdir ('/'):
5. If Fnmatch.fnmath (fileName, ' *.txt '):
6. Print open (fileName). Read ()
7. Elif Fnmatch.fnmatch (fileName, ' *.exe '):
8. Print FileName

Import Fnmatch
Import OS

For FileName in Os.listdir ('/'):
If Fnmatch.fnmath (fileName, ' *.txt '):
Print open (fileName). Read ()
Elif Fnmatch.fnmatch (fileName, ' *.exe '):
Print FileName

The "*" character can represent any length of character. If you want to match one character, use the "?" Symbol:

1. Import Fnmatch
2. Import OS
3.
4. For fileName in Os.listdir ('/'):
5. If Fnmatch.fnmatch (FileName, '?. TXT '):
6. print ' Text file. '

Import Fnmatch
Import OS

For FileName in Os.listdir ('/'):
If Fnmatch.fnmatch (FileName, '?. TXT '):
print ' Text file. '

The "Fnmatch" module supports regular expressions:

1. Import Fnmatch
2. Import OS
3. Import re
4.
5. Filepattern = Fnmatch.translate (' *.txt ')
6. For fileName in Os.listdir ('/'):
7. If Re.match (Filepattern, FileName):
8. print ' Text file. '

Import Fnmatch
Import OS
Import re

Filepattern = fnmatch.translate (' *.txt ')
For FileName in Os.listdir ('/'):
If Re.match (Filepattern, FileName):
print ' Text file. '

If you only need to match one type of file, a better approach would be to use the "Glob" module. The format of the module is similar to "Fnmatch":

1. Import Glob
2.
3. For fileName in Glob.glob (' *.txt '):
4. print ' Text file. '

Import Glob

For FileName in Glob.glob (' *.txt '):
print ' Text file. '

It is also possible to match a range of characters, just as you would in regular expressions. Suppose you want to display the filename of a file with only one digit before the extension:

1. Import Glob
2.
3. For fileName in Glob.glob (' [0-9].txt '):
4. Print filename

Import Glob

For FileName in Glob.glob (' [0-9].txt '):
Print filename

The "Glob" module is implemented using the "Fnmatch" module.

Iv. Data Grouping
Use the module described in the previous section to enable reading and writing of strings in a file.
Sometimes, however, you may need to pass other types of data, such as list, tuple, dictionary, and other objects. In Python, you can use pickling to do this. You can use the "pickle" module in the Python standard library to complete data grouping.
Next, we'll group A list that contains strings and numbers:

1. Import Pickle
2.
3. FileHandle = open (' PickleFile.txt ', ' W ')
4. testlist = [' This ', 2, ' is ', 1, ' A ', 0, ' Test. ']
5. Pickle.dump (Testlist, FileHandle)
6. Filehandle.close ()

Import Pickle

FileHandle = open (' PickleFile.txt ', ' W ')
Testlist = [' This ', 2, ' is ', 1, ' A ', 0, ' Test. ']
Pickle.dump (Testlist, FileHandle)
Filehandle.close ()

Splitting the grouping is also easy:

1. Import Pickle
2.
3. FileHandle = open (' PickleFile.txt ')
4. testlist = Pickle.load (filehandle)
5. Filehandle.close ()

Import Pickle

FileHandle = open (' PickleFile.txt ')
Testlist = Pickle.load (filehandle)
Filehandle.close ()

Now try to store more complex data:

1. Import Pickle
2.
3. FileHandle = open (' PickleFile.txt ', ' W ')
4. testlist = [123, {' Calories ': 190}, ' Mr Anderson ', [1, 2, 7]]
5. Pickle.dump (Testlist, FileHandle)
6. Filehandle.close ()

Import Pickle

FileHandle = open (' PickleFile.txt ', ' W ')
Testlist = [123, {' Calories ': 190}, ' Mr Anderson ', [1, 2, 7]]
Pickle.dump (Testlist, FileHandle)
Filehandle.close ()

1. Import Pickle
2.
3. FileHandle = open (' PickleFile.txt ')
4. testlist = Pickle.load (filehandle)
5. Filehandle.close ()

Import Pickle

FileHandle = open (' PickleFile.txt ')
Testlist = Pickle.load (filehandle)
Filehandle.close ()


As mentioned, using Python's "pickle" module grouping is really simple. Many objects can be stored in a file through it. If you can, "Cpickle" is also competent for this job. It's the same as the "pickle" module, but faster:

1. Import Cpickle
2.
3. FileHandle = open (' PickleFile.txt ', ' W ')
4. Cpickle.dump (1776, FileHandle)
5. Filehandle.close ()

Import Cpickle

FileHandle = open (' PickleFile.txt ', ' W ')
Cpickle.dump (1776, FileHandle)
Filehandle.close ()

V. Create a "virtual" file
Many of the modules you use contain methods that require file objects as parameters. However, sometimes creating and using a real file makes people feel a little bit of trouble. Fortunately, in Python, you can use the "Stringio" module to create a file and save it in memory:

1. Import Stringio
2.
3. FileHandle = Stringio.stringio ("Let Freedom Ring")
4. Print filehandle.read () # "Let the Freedom Ring."
5. Filehandle.close ()

Import Stringio

FileHandle = Stringio.stringio ("Let Freedom Ring")
Print Filehandle.read () # "Let the Freedom Ring."
Filehandle.close ()

Cstringio "module is also valid. It is used in the same way as "Stringio", but like "cpickle" for "Pickle", it is faster:

1. Import Cstringio
2.
3. FileHandle = Cstringio.cstringio ("To Kill a Mockingbird")
4. Print filehandle.read () # "to Kill a Mockingbid"
5. Filehandle.close ()

Import Cstringio

FileHandle = Cstringio.cstringio ("To Kill a Mockingbird")
Print Filehandle.read () # "to Kill a Mockingbid"
Filehandle.close ()

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.