python study notes (22) -os file operation module

doubt:

If you open a file operation is good or absolute path to a relative path?

os module, in the following lib, can be directly introduced directly import.

First, create a new directory, create a new folder

import os

# Create a new folder

os.mkdir("wuzm")

# Create cross-level directory, with different levels / symbol represents the path of the need to ensure top level is there.

os.mkdir ( "wuzm / lyn") # relative path

os.mkdir ( "D: \\ test_python") # absolutely path \ escape character, \ t tab. We can \ r or preceded by an escape character, or R to failure.

 

Second, delete

os.rmdir ( "wuzm / lyn") # delete a file is to delete a level not recommended a one-time delete

os.remove ( "wuzm / lyn") # If wuzm below lyn, you can not delete this file only wuzm

 

# Expand: 1, python whether mandatory deleted

# 2, how to create a new file, open a new can, how to delete files

 

Third, the acquisition path

Path Gets 1: Get the current working directory, the directory specific to the last stage

path = os.getcwd()

print ( "The current path is acquired: {0}". format (path))

 

# Path Gets 2: Get the absolute path of the current file, specific to the module name

path_2 = os.path.realpath (__ file__) #__file__ static variables, the identification module itself

print ( "The current path is acquired: {0}". format (path_2))

 

'' 'Output:

Acquired the current path is: E: \ lemon first week of classes

Acquired the current path is: E: \ lemon classes the first week \ lianxi.py '' '

 

Fourth, how to splice path

#method one:

new_path_1 = os.getcwd () + "\ pathon1" # splicing a path, a need to add \

print(new_path_1)

os.mkdir (new_path_1) # This creates a new path

#Method Two:

#new_path_2 = os.path.join(os.getcwd(),"python666\sub1")

new_path_2 = os.path.join (os.getcwd (), "python666", "sub1") # Here is a variable length parameter, a new class can not cross the path must exist in front of the

print(new_path_2)

os.mkdir(new_path_2)

 

 

Guess you like

Origin www.cnblogs.com/wuzm/p/11838361.html