Python Directory file Operations Daquan

Source: Internet
Author: User
Tags readline python script

Directory Operations


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

>>> Import OS

>>> OS.GETCWD ()

'/home/jack '

2. Return all files and directories under the specified directory name: Os.listdir ()

>>> os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', ' Test ', '. Bash_logout ']

3. function to delete a file: Os.remove ()

#创建文件 >>> Os.mknod ("T1.txt")


#显示当前目录下的所有文件

>>> os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', ' t1.txt ', ' Test ', '. Bash_logout ']


#删除文件

>>> os.remove ("T1.txt")

>>> os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', ' Test ', '. Bash_logout ']

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


#创建多个目录

>>> os.makedirs ("T1/t2")

>>> os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', ' t1 ', ' Test ', '. Bash_logout ']

>>> os.listdir ('/home/jack/t1 ')

[' T2 ']

#删除多个目录

>>> Os.removedirs (r "/home/jack/t1/t2")

Os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', ' Test ', '. Bash_logout ']

5. Check if the given path is a file: Os.path.isfile ()

>>> os.path.isfile ('. BASHRC ')

True

>>> os.path.isfile ('. Bashrc1 ')

False

6. Check if the given path is a directory: Os.path.isdir ()

>>> os.path.isdir ('/home/jack/test ')

True

>>> os.path.isdir ('/home/jack/test1 ')

False

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

>>> os.path.isabs ('/home/jack/test ')

True

>>> os.path.isabs (' test ')

False

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

>>> os.path.exists (' test ')

True

>>> os.path.exists (' test1 ')

False

9. Returns the directory name and file name of a path: Os.path.split ()

>>> os.path.split ('/home/jack/test ')

('/home/jack ', ' test ')


10. Detach extension: Os.path.splitext ()

>>> os.path.splitext ('/home/jack/test ')

('/home/jack/test ', ')


11. Get Path name: Os.path.dirname ()

>>> os.path.dirname ('/home/jack/')

'/home/jack '


12. Get File Name: Os.path.basename ()

>>> Os.mknod (' a.txt ')

>>> os.path.basename ('/home/jack/a.txt ')

' A.txt '

13. Run shell command: Os.system ()

>>> os.system (' ls-a ')

.  .. A.txt. bash_logout. bashrc. Profile Test


14. Read and SET environment variables: os.getenv () and os.putenv ()


Getenv (Key, Default=none)

Get an environment variable, return None if it doesn ' t exist.

The optional second argument can specify an alternate default.

15. Renaming: Os.rename (old, new)

>>> Import OS

>>> Os.listdir ("/home/jack")

['. Profile ', ' a.txt ', '. BASHRC ', '. Bash_history ', '. Ipython ', ' Test ', '. Bash_logout ']

>>> os.rename (' a.txt ', ' b.txt ')

>>> os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', '. Bash_history ', '. Ipython ', ' b.txt ', ' Test ', '. Bash_logout ']


16. Create multilevel directory: Os.makedirs ()

>>> os.makedirs (' t1/t2 ')

>>> os.listdir ('/home/jack ')

['. Profile ', '. BASHRC ', '. Bash_history ', '. Ipython ', ' t1 ', ' b.txt ', ' Test ', '. Bash_logout ']

>>> os.listdir ('/home/jack/t1 ')

[' T2 ']

17. Create a single directory: Os.mkdir ()

>>> os.mkdir (' abc ')

>>> os.listdir ('/home/jack ')

['. Profile ', ' abc ', '. BASHRC ', '. Bash_history ', '. Ipython ', ' t1 ', ' b.txt ', ' Test ', '. Bash_logout ']


18, get File attributes: Os.stat (file)

>>> os.stat (' B.txt ')

Posix.stat_result (st_mode=33152, st_ino=927137, st_dev=64769, St_nlink=1, st_uid=1001, st_gid=1001, st_size=0, St_ atime=1510235921, st_mtime=1510235921, st_ctime=1510277660)


19. Modify file permissions and timestamps: Os.chmod (file)


Reference Blog: http://blog.csdn.net/wirelessqa/article/details/7974477


20. Terminate the current process: Os.exit ()


21. Get File Size: os.path.getsize (filename)

>>> os.path.getsize (' B.txt ')

0


File operations

Os.mknod ("Test.txt") #创建空文件
fp = open ("Test.txt", W) #直接打开一个文件, create file If file does not exist

R: Open the file in read mode to read the file information.

W: Open the file in writing and write information to the file. If the file exists, the file is emptied, the new content is written, and the file is created if it does not exist

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

r+: Open the file in read and write mode, can read and write the file.

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

A +: Open the file in read-write mode and move the file pointer to the end of the file.

B: Open the file in binary mode instead of in text mode. This mode is only valid for Windows or DOS, and Unix-like files are operated in binary mode.


File Operation methods


Common file operation methods:

Method

F.close () Close the file, remember to open the file after opening () must remember to close it, otherwise it will occupy the system open file handle number.

F.name () Get file name


F.next () returns to the next line 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.


F.flush () Refreshes the output cache and writes the contents of the buffer to the hard disk

F.isatty () returns True if the file is a terminal device file (Linux system), otherwise false is returned.

F.read ([size]) reads the file, size is the length of the read, in bytes

F.readline ([size]) reads a line of information, and if size is defined, a portion of the line is read

F.readlines ([size]) reads all the rows, that is, the information that reads the entire file. (Take each line of the file as a member of a list and return to 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)

F.seek (Offset[,where])

Move the file pointer to the offset position relative to where. Where 0 indicates the beginning of the file, this is the default, 1 is the current position, and 2 means the end of the file. (Note: If the file is open in a or a + mode, the file action tag will automatically return to the end of the file each time you write)

F.tell () Gets the position of the file pointer, marks the current position, and begins with the origin of the file.

F.truncate ([size]) cuts the file to the specified size, and the default is the position of 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.

F.write (String) writes string strings to the file, and write () does not add a newline character after Str.

F.writelines (list) writes a string of strings in a list to a file in a row, which is written continuously, with no newline.


Example of file operation mode


W mode, if there is no file, it will be created automatically

>>> os.listdir ('/home/jack ') ['. Profile ', ' abc ', '. BASHRC ', '. Bash_history ', '. Ipython ', ' t1 ', ' b.txt ', ' Test ' , '. Bash_logout ']>>> f1 = open (' Hello.txt ', ' W ') >>> f1.write (' Hello world\n ') >>> F1.flush () #刷新输出缓存, write the contents of the buffer to HDD >>> f1.close ()

R-mode read-only mode

>>> f1 = open (' Hello.txt ', ' R ') >>> print (F1.read ()) Hello World


The r+ mode opens the file in both read and write format, which can be used for reading and writing files. Will empty the original file

>>> f1 = open (' Hello.txt ', ' r+ ') >>> f1.write (' Hello2 world\n ') >>> f1.close () >>> F1 = Open (' Hello.txt ', ' R ') >>> print (F1.read ()) Hello2 World


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

>>> f1 = open (' Hello.txt ', ' w+ ') >>> f1.write (' Hello World, Hello world\n ') >>> f1.close () > >> f1 = open (' Hello.txt ', ' R ') >>> print (F1.read ()) Hello World, Hello World


A mode opens the file in Append mode (that is, an open file, the file pointer is automatically moved to the end of the file)

Created if the file does not exist, the original file content is retained

>>> f1 = open (' Hello.txt ', ' a ') >>> f1.write (' H2 h2\n ') >>> f1.close () >>> f1 = open (' Hello.txt ', ' R ') >>> print (F1.read ()) Hello World, hello WORLDH2 H2


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

>>> f1 = open (' Hello.txt ', ' A + ') >>> f1.write (' H3 h3 h3\n ') >>> f1.close () >>> f1 = Open (' Hello.txt ', ' R ') >>> print (F1.read ()) Hello World, hello worldh2 h2h3 h3 h3

B: Mode is typically used for binary file operations


File read and Write methods

Read # reads out all files, size is the length of the read, in bytes



ReadLine #一行一行的读取



ReadLines #读出所有行, that is, the information that reads the entire file. (Take each line of the file as a member of a list and return to 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)


F.write (String) writes string strings to the file, and write () does not add a newline character after Str.

F.writelines (list) writes a string of strings in a list to a file in a row, which is written continuously, with no newline.





This article is from the "Sdsca" blog, make sure to keep this source http://sdsca.blog.51cto.com/10852974/1980534

Python Directory file Operations Daquan

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.