Detailed usage of programming language python os module

Detailed usage of programming language python os module

The os module provides very rich methods for handling files and directories

os about directory path

# Get current path
path = os.getcwd()

# Gets the current absolute path
os.path.abspath(path)
 
# Create first level directory
os.mkdir(path)

# remove empty directories
os.rmdir(path)

# Create multi-level directory
os.makedirs(path)

# Delete multilevel empty directory
os.removedirs(path)

# Modify the path to path
os.chdir(path)

Include knowledge points

  • rmdir path. If the directory is not empty, an OSError exception will be thrown
  • Multilevel directories refer to / test/testing/test. If none of the three directories exist, they will be created

os methods for files

# Get all files and folders under the current path
os.listdir(path)

# Create file method 1
f = os.open(path + "test.txt", flags=os.O_CREAT | os.O_RDWR )

# write file
os.write(f, bytes("123",encoding="utf-8"))

# read file
print(os.read(f,12))

# Close file
os.close(f)

# rename file
os.rename(path + "test.txt", path + "tests.txt")

# Delete file
os.remove(path + "tests.txt")
# Recursively returns the triple of directory (including path directory), subdirectory and file name under path
for root, dirname, filenames in os.walk(path):
    logzeros.debug(root)
    logzeros.debug(dirname)
    logzeros.debug(filenames)

Include knowledge points

  • listdir returns a list. If there is no file, it returns an empty list

  • os.write(fd, str) is used to write the bytes string into the file descriptor fd. Returns the length of the actually written string

  • os.read(fd,n) is used to read up to n bytes from the file descriptor fd and return a string containing bytes

os.path related

os.path.realpath(__file__)

Get the directory where the current file is located

path = os.path.realpath(__file__)
print(path)

Operation results

C:\Users\user\Desktop\py\moocInterface\learn\os_path_learn.py

os.path.abspath(path)

Get the path where the current path is located

#Python learning exchange group: 725638078
path = os.path.abspath(".")
print(path)

path = os.path.abspath(os.path.realpath(__file__))
print(path)

Operation results

C:\Users\user\Desktop\py\moocInterface\learn
C:\Users\user\Desktop\py\moocInterface\learn\os_path_learn.py

The first line is similar to os.getcwd()

path = os.getcwd()
print(path)

Operation results

C:\Users\user\Desktop\py\moocInterface\learn

os.path.dirname(path)
Returns the path of the directory where path is located

print(os.path.dirname(r'C:\Users\user\Desktop\py\moocInterface\learn\os_path_learn.py'))

print(os.path.dirname(r'C:\Users\user\Desktop\py\moocInterface\learn'))

# Indicates the upper level directory of the directory where the current file is located, that is, the project directory C:\Users\user\Desktop\py\moocInterface
print(os.path.dirname(os.path.abspath('.'))) 

Operation results

C:\Users\user\Desktop\py\moocInterface\learn
C:\Users\user\Desktop\py\moocInterface
C:\Users\user\Desktop\py\moocInterface

os.path.split(path)
Separate the file name and extension, and return the binary (filename, fileextension)

# catalogue
os.path.split(os.getcwd())

# file
os.path.split(os.path.realpath(__file__))

Operation results

('C:\\Users\\user\\Desktop\\py\\moocInterface', 'learn')
('C:\\Users\\user\\Desktop\\py\\moocInterface\\learn', 'os_path_learn.py')

os.path.join()
Used for path splicing. Multiple paths are combined and returned. The parameters before the first absolute path will be ignored

#Python learning exchange group: 725638078
# Splice catalog
new_path = os.path.join(os.getcwd(), "test")
print(new_path)

# Splice file
new_path = os.path.join(os.getcwd(), "test.txt")
print(new_path)

# Splice multiple directories
new_path = os.path.join(os.getcwd(), "test/test/test")
print(new_path)

# Splicing multiple directories and files
new_path = os.path.join(os.getcwd(), "test", "Test", "ok.txt")
print(new_path)

Operation results

C:\Users\user\Desktop\py\moocInterface\learn\test
C:\Users\user\Desktop\py\moocInterface\learn\test.txt
C:\Users\user\Desktop\py\moocInterface\learn\test/test/test
C:\Users\user\Desktop\py\moocInterface\learn\test\Test\ok.txt

At the end, I recommend a very good learning tutorial for you. I hope it will be helpful for you to learn Python!

Python basic introductory tutorial recommendation: more Python Video Tutorials - pay attention to station B: Python learners
[Python tutorial] 1000 sets of Python system learning tutorials that are the easiest to understand in the whole network (Q & A in the last four issues, full of dry goods)_ Beep beep beep_ bilibili

Python crawler case tutorial recommendation: more Python Video Tutorials - follow site B: Python learners
2021 Python latest 100 complete case tutorials of crawlers, data analysis, data visualization, remember to collect_ Beep beep beep_ bilibili

Article source: https://www.cnblogs.com/xxpythonxx/p/15530754.html

Wow Education
www.awaedu.com
Composition brother
www.zuowenge.cn
Search the code
www.somanba.cn
Brother Cheng
www.jcdi.cn

Tags: Python Back-end

Posted on Wed, 10 Nov 2021 20:47:08 -0500 by Marqis