Summary of common basic operations for Python files and folders

  • 2020-05-12 02:48:07
  • OfStack

This article illustrates common basic operations for Python files and folders. I will share it with you for your reference as follows:

1. Determine whether the file (folder) exists.


os.path.exists(pathname)

2. Determine whether the path name is a file.


os.path.isfile(pathname)

3. Determine whether the path name is a directory.


os.path.isdir(pathname)

4. Create files.


os.mknod(filename)  #windows Is not available when 
open(filename, "w")  # Remember to close 

5. Copy files.


shutil.copyfile("oldfile", "newfile")  #oldfile and newfile They can only be files 
shutil.copy("oldfile", "newfile")  #oldfile Only documents, newfile It can be a file or a target directory 

6. Delete files.


os.remove(filename)

7. Empty the file.


file = open("test.txt", w)
file.seek(0)
file.truncate() # Notice the location of the file pointer 
file.close()

8. Create a directory.


os.mkdir(pathname)    # Create a single-level directory 
os.makedirs(pathname)   # Recursively create multiple levels of directories 

9. Copy the directory.


shutil.copytree("olddir", "newdir")
#olddir and newdir They can only be directories, and newdir Must not exist 

Rename a file or directory.


os.rename(oldname, newname)

11. Move files or directories.


os.path.isfile(pathname)

0

12. Delete the directory.


os.path.isfile(pathname)

1

12.1. Empty the directory.


os.path.isfile(pathname)

2

13. Switch directories.


os.chdir(newpath)

14. Common mode of open

'r': read only (default). If the file does not exist, an error is thrown.
'w': write only (if the file does not exist, the file is automatically created.)
'a: additional
'r + : reading and writing

15, from the full path name to the path and file name.


os.path.isfile(pathname)

4

16. Get the file size.


os.path.isfile(pathname)

5

Get the absolute path to the current file directory.


os.path.isfile(pathname)

6

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.


Related articles: