Python-based file read and write

Source: Internet
Author: User
Tags python script

Python-based files read and write this section
    1. Some methods of files and directories in the OS module
    2. Operation of the file
    3. Operation of the Directory
Some methods of files and directories in the 1.os module

Some of the ways in which Python operations files and directories can use OS modules are as follows:

  1. Get the current working directory, that is, the directory path of the current Python script work: OS.GETCWD ()
  2. Returns all files and directory names in the specified directory, returning a list: Os.listdir ("Specify Path")
  3. function to delete a file: Os.remove ("File path")
  4. Delete multiple directories: os.removedirs ("directory Path")
  5. Verifies whether the given path is a file and returns a bool value: Os.path.isfile ("Specify Path")
  6. Verifies whether the given path is a directory and returns a bool value: Os.path.isdir ("directory Path")
  7. To determine if it is an absolute path, return a bool value: Os.path.isabs ("Specify Path")
  8. Verifies that the given path exists and returns a bool value: os.path.exists ("Specify Path")
  9. Returns the directory name and file name of a path, returns a tuple, separates the file name and directory name: Os.path.split ("specified path") Results of eg Os.path.split ('./test.txt '): ('. ', ' test.txt ')
  10. Detach the extension, return a tuple, split the file name with the preceding path and the following extension: Os.path.splitext ("Specify Path")
  11. Gets the path name, intercepts the path in front of the file in the specified path and returns: Os.path.dirname ("Specify Path")
  12. Gets the filename, intercepts the file name in the specified path, and returns: Os.path.basename ("Specify Path")
  13. Run the shell command and return to the command execution result: Os.system ("command")
  14. Read and SET Environment variables: os.getenv () and os.putenv ()
  15. Gives the line terminator used by the current platform: os.linesep Windows uses ' \ r \ n ', Linux uses ' \ n ' and Mac uses ' \ R '
  16. Indicates the platform you are using: Os.name for Windows, it is ' nt ' or ' CE ' (Windows CE is an open, upgradeable 32-bit embedded operating system), and for Linux/unix users, it is ' POSIX '
  17. Rename: Os.rename ("Oldname", "NewName")
  18. Create a multilevel directory: Os.makedirs ("Multilevel directory")
  19. Create a single directory: Os.mkdir ("Test")
  20. Get file properties: Os.stat ("file name")
  21. Modify file permissions and timestamps: Os.chmod ("file name")
  22. Terminate current process: Os.exit ()
  23. Get File Size: os.path.getsize ("filename")
2. Operation of the file

The file operation uses the Open function to get the file handle generated by the file object, and the open function passes the parameter ("File path", "mode option", encoding= "encoding Mode")

Mode options:

    1. "R" opens in read-only file, exception occurs if the file does not exist
    2. "W" is opened in writing, only the file is written, and if the file does not exist, the file is created. If the file already exists, empty it before opening the file
    3. The "A" opens in Append mode, only the file is written, and if the file does not exist, the file is created. If the file already exists, start with EOF.
    4. "R+" opens in read-write mode, does not empty the file, reads the cursor at the beginning, and writes the cursor at the very end of the position.
    5. "w+" opens in read-write mode, emptying files and supporting read/write.
    6. "A +" opens in read-write mode with the cursor at the very end.
    7. The "RB" is opened in binary read mode and can read only the file, and if the file does not exist, an exception occurs.
    8. "WB" is opened as binary write, can only write files, if the file does not exist, create the file. If the file already exists, empty it before opening the file.
    9. "RT" opens as a text read, can only read a file, and if the file does not exist, an exception occurs
    10. "WT" is opened as text and can only be written to the file, if the file does not exist, the file is created. If the file already exists, empty it before opening the file
    11. "Rb+" is opened in binary read, can read, write the file, if the file does not exist, an exception will occur
    12. The "wb+" is opened in binary write, can read, write the file, if the file does not exist, create the file. If the file already exists, empty it before opening the file
The methods provided by the file object:
  1. F.read ([size]) #size为读取的长度, in bytes (all content is read by default without parameters)
  2. F.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
  3. F.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the list. In fact, its internal is through the Loop tune 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.
  4. F.write (str) #把str写到文件中, write () does not add a newline character after Str
  5. F.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.
  6. F.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
  7. F.flush () #把缓冲区的内容写入硬盘
  8. F.fileno () #返回一个长整型的 "file label"
  9. F.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
  10. F.tell () #返回文件操作标记的当前位置, starting with the origin of the file
  11. F.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.
  12. F.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.
  13. F.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 added up
3. Operation of the Directory

To create a directory:

os.mkdir("file")

To copy a file:

shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件shutil.copy("oldfile","newfile")#oldfile只能是文件夹,newfile可以是文件,也可以是目标目录

To copy a folder:

shutil.copytree("olddir","newdir")#olddir和newdir都只能是目录,且newdir必须不存在

Rename file (directory):

os.rename("oldname","newname")#文件或目录都是使用这条命令

Moving Files (directories):

shutil.move("oldpos","newpos")   

To delete a file:

os.remove("file")

To delete a directory:

os.rmdir("dir")#只能删除空目录shutil.rmtree("dir")#空目录、有内容的目录都可以删

To convert a directory:

os.chdir("path")#切换路径

Python-based file read and write

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.