English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article describes some common basic operations on Python files and folders. Shared for everyone's reference, as follows:
1Determine if the file (folder) exists.
os.path.exists(pathname)
2Determine if the pathname is a file.
os.path.isfile(pathname)
3Determine if the pathname is a directory.
os.path.isdir(pathname)
4Create a file.
os.mknod(filename) # not available on Windows open(filename, "w") # remember to close
5Copy file.
shutil.copyfile("oldfile", "newfile") # Both oldfile and newfile can only be files shutil.copy("oldfile", "newfile") # oldfile can only be a file, newfile can be a file or a target directory
6Delete file.
os.remove(filename)
7Clear file.
file = open("test.txt", w) file.seek(0) file.truncate() # Note the position of the file pointer file.close()
8Create directory.
os.mkdir(pathname) # Create a single-level directory os.makedirs(pathname) # Recursively create multi-level directories
9Copy directory.
shutil.copytree("olddir", "newdir") # Both olddir and newdir can only be directories, and newdir must not exist
10Rename file or directory.
os.rename(oldname, newname)
11Move file or directory.
shutil.move(oldpath, newpath)
12Delete directory.
os.rmdir("dir") # Cannot delete non-empty directories ''' # Can delete non-empty directories, even if the directory is open # Approximately equal to 'rd /Q /S dir' ''' shutil.rmtree("dir")
12.1Clear directory.
# encoding=utf-8 # For Python3.5+ import os, sys, time, shutil # Clear directory print('ClearDir ' + dir + '...') for entry in os.scandir(dir): if entry.name.startswith('.'): continue if entry.is_file(): os.remove(entry.path) # Delete file else: shutil.rmtree(entry.path) # Delete directory
13Change directory.
os.chdir(newpath)
14Common open modes of 'open'.
'r': Only read (Default. If the file does not exist, an error will be thrown.)
'w': Only write (If the file does not exist, it will be automatically created.)
'a': Append
'r'+': Read and Write
15、Get the path and file name from the full path name.
>>> pathfile = r'D:\abc\def\ghi.txt' >>> os.path.dirname(pathfile) 'D:\\abc\\def' >>> os.path.basename(pathfile) 'ghi.txt'
16、Get the file size.
os.path.getsize(pathfile) # Unit in bytes (Byte)
17、Get the absolute path of the current file directory.
import os, sys if __name__ == "__main__": os.chdir('E:\\') print(sys.path[0]) print(os.path.abspath('.')) print(os.path.dirname(os.path.abspath(__file__)))
Readers who are interested in more content related to Python can check the special topics on this site: 'Summary of Python File and Directory Operation Skills', 'Summary of Python Text File Operation Skills', 'Summary of Python URL Operation Skills', 'Summary of Python Image Operation Skills', 'Python Data Structures and Algorithms Tutorial', 'Summary of Python Socket Programming Skills', 'Summary of Python Function Usage Skills', 'Summary of Python String Operation Skills', and 'Classic Tutorial of Python Entry and Progression'.
I hope the content described in this article will be helpful to everyone in designing Python programs.
Declaration: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace '#' with '@' when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the content suspected of infringement.