1. Read the contents of the file
Import Codecs
F=codecs.open (' 1.txt ', ' RB ')
Print (F.read ())
F.close ()
2. Write a new file
Import Codecs
F=codecs.open (' 2.txt ', ' WB ')
F.write (' Hello World ')
F.close ()
Special usage of 3.With
Import Codecs
With Codecs.open (' 1.txt ', ' RB ') as F:
Print (F.read ())
Print (f.closed)
Special use of 4.Codecs
One of the important functions in the codecs module is lookup, which has only one parameter encoding, which refers to the name of the encoding method, i.e. utf-8 or gb2312, etc.;
Import Codecs
t = codecs.lookup ("Utf-8")
Encoder = T[0]
Decoder = t[1]
StreamReader = t[2]
StreamWriter = t[3]
The codecs module also provides a separate function that is convenient for programmers to use:
Getencoder (encoding)
Getdecoder (encoding)
Getreader (encoding)
Getwriter (encoding)
5. Common methods for file operation
Python in the file, folder operations often used in the OS module and Shutil module common methods;
1. Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()
2. Return all files and directories under the specified directory name: Os.listdir ()
3. function to delete a file: Os.remove ()
4. Delete multiple directories: Os.removedirs (r "C:\python")
5. Verify that the given path is a file: Os.path.isfile ()
6. Verify that the given path is a directory: Os.path.isdir ()
7. Determine if it is an absolute path: Os.path.isabs ()
8. Verify that the given path is really saved: os.path.exists ()
9. 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 ')
10. Detach extension: Os.path.splitext ()
11. Get Path name: Os.path.dirname ()
12. Get File Name: Os.path.basename ()
13. Run the shell command: Os.system ()
14. Read and SET environment variables: os.getenv () and os.putenv ()
15. Give the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
16. Indicate the platform you are using: Os.name for Windows, it is ' NT ', and for Linux/unix users, it is ' POSIX '
17. Renaming: Os.rename (old, new)
18. Create a multilevel directory: Os.makedirs (r "C:\python\test")
19. Create a single directory: Os.mkdir ("Test")
20. Get File attributes: Os.stat (file)
21. Modify file permissions and timestamps: Os.chmod (file)
22. Terminate the current process: Os.exit ()
23. Get File Size: os.path.getsize (filename)
File Operation Method:
1.os.mknod ("Test.txt") #创建空文件
2.FP = open ("Test.txt", W) #直接打开一个文件, create file If file does not exist
3. About open mode:
W: Open in write mode,
A: Open in Append mode (starting with EOF and creating a new file if necessary)
r+: Open in read-write mode
w+: Open in read/write mode (see W)
A +: Open in read/write mode (see a)
RB: Open in binary read mode
WB: Opens in binary write mode (see W)
AB: Open in binary append mode (see a)
rb+: Open in binary read/write mode (see r+)
wb+: Open in binary read/write mode (see w+)
ab+: Open in binary read/write mode (see A +)
Fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only one part of the line
Fp.readlines ([ Size]) #把文件每一行作为一个list的一个成员 and return to this 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
Fp.writelines (seq) #把seq的内容全部写到文件中 after str (multi-line write-once). This function simply writes faithfully and does not add anything behind each line. The
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. ValueError
Fp.flush () #把缓冲区的内容写入硬盘
Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () # If a file is also manipulated after it has been closed Whether the file is a terminal device file (Unix system)
Fp.tell () #返回文件操作标记的当前位置, #返回下一行 the beginning of the file as the Origin
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 operation method:
1. Create a Directory
Os.mkdir ("file")
2. Copy the file:
Shutil.copyfile ("Oldfile", "NewFile") #oldfile和newfile都只能是文件
Shutil.copy ("Oldfile", "NewFile") #oldfile只能是文件夹, NewFile can be a file, or it can be a destination directory
3. Copy the folder:
4.shutil.copytree ("Olddir", "Newdir") #olddir和newdir都只能是目录, and newdir must not exist
5. Renaming files (directories)
Os.rename ("Oldname", "NewName") #文件或目录都是使用这条命令
6. Moving Files (directories)
Shutil.move ("Oldpos", "Newpos")
7. deleting files
Os.remove ("file")
8. Deleting a directory
Os.rmdir ("dir") #只能删除空目录
Shutil.rmtree ("dir") #空目录, contents of the directory can be deleted
9. Converting a directory
Os.chdir ("path") #换路径
Python Exercises (ii)