xls6-python python parsing properties files Notes (a) get the current directory path and file

 
python notes (a) to get the current directory path and file
 

First, get the current path

 

      1, using sys.argv [0]

SYS Import 
Print the sys.argv [0] 
# output
# local path

     

      2, os module

Copy the code
os Import 
Print os.getcwd () # Get the current working directory path 
print os.path.abspath ( '.') # get the current working directory path 
print os.path.abspath ( 'test.txt') # get the files in the current directory the working directory path 
print os.path.abspath ( '..') # get the parent directory of the current working! Note that the parent directory path 
print os.path.abspath (os.curdir) # Get the current working directory path
Copy the code

 

 

    3, change the current directory

         1) Use: os.chdir (path).

         For example, if the current directory in the 'E:' below, and then enter the following files E files can be used os.chdir (E: \ files).

         Thereafter, for example, test1 = open ( 'file1.txt'), the file will be opened in the 'E: \ files' directory under the file, rather than the 'E' under.

   

    4, the return path combination

         os.path.join('file1','file2','file3')

         Were combined to obtain path file1 / file2 / file3

>>> print os.path.join('E:', 'file1', 'file2')
E:/file1/file2
>>> print os.path.join('/home', '/home/file1/', '/home/file1/file2/')
/home/file1/file2/

        no.2

Copy the code
os Import 
root = os.getcwd () # get current path / Home / dir1 
Print root 
# output 
# / Home / dir1 

name = "file1" # define the file name of the   
print (os.path.join (root, name) ) # merge path names and file names, and print 
# output 
# / home / dir1 / file1
Copy the code

      

 

Second, access to all files in the current directory

      1. os.walk () in the directory for the file name of the output directory tree walk up or down;

Copy the code
Syntax 
os.walk (top [, topdown = True [, onerror = None [, followlinks = False]]]) 

Parameters: Top - each clip file in the root directory (including itself), to produce 3-tuple ( dirpath, dirnames, filenames) [folder path
folder name, file name]. topdown - Alternatively, or not specified is True, a 3-tuple directory 3- tuple than its subfolders the first generation (directory top-down).
If topdown is False, 3- tuple than generating a directory (directory bottom-up) after the group of 3-membered to its subfolders. onerror - Alternatively, a function; it has a parameter called a OSError example. After reporting this error, continue to walk, or throw an exception terminated walk. followlinks - set to true, then by a soft link to access the directory.
Copy the code

    2.

Copy the code
os Import 
root = os.getcwd () 

DEF file_name (file_dir): 
    for root, dirs, Files in os.walk (file_dir): 
        Print "-----------" 
        Print root # os.walk ( ) directory 
        for all directory names print dirs # os.walk () directory of 
        print files # os.walk all non-directory file name () directory of 
        Print "" 

file_name (root)
Copy the code

  -----------  ---------- ----

 

 

 

 

 

xls6-python parsing properties files

# -*- coding:utf-8 -*-
import time as t
import cx_Oracle as oracle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random,os,math,re,time
import properties09 as prop
def main():
file_path = r'D:\backup\PycharmProjects\charm123\prop.properties'
dictProperties=prop.Properties(file_path).getProperties()
print (dictProperties)
print (type(dictProperties))
print (len(dictProperties))
print (dictProperties['username'])
print (dictProperties['url'])
print (dictProperties['driver'])
hang1=1
try:
hang1=dictProperties['hang1']
the except:
hang1 = 0
Print (hang1)
hang1. 1 =
the try:
hang1 dictProperties = [ 'Hang']
the except:
hang1 = 0
Print (hang1)
Print (os.curdir)
Print (os.pardir)
Print (os.defpath)
Print (os.path)


main ()



Import os


Print ( "=== === get the current directory")
# current directory path to the script work
print ( 'os.getcwd () script before working directory path:', os .getcwd ())
# os.path.abspath () to get the absolute path
print ( 'os.path.abspath () to get the absolute path:', os.path.abspath (os.path.dirname (__ file__)))

Print ( "get the current file-level directory === ===")
Print ( "get the current file-level directory === == 1 =", os.path.abspath (os.path.dirname (os.path.dirname (__ file__ ))))
print ( "=== get the parent directory of the current file 2 = ==", os.path.abspath (os.path.dirname (os.getcwd ())))
print ( "=== == get the current file parent directory =. 3 ", os.path.abspath with (the os.path.join (The os.getcwd ()," .. ")))
Print (" Get the current file-level directory === == 4 = ", os.path. dirname (os.getcwd ()))
# os.path.join () connected directory name and file or directory


print ( "==== set the path for the test_case files in the current folder parent directory ====")
path = os.path.join (os.path.dirname (os.getcwd ()), "test_case")
Print ( "==== set the path for the test_case files in the current folder parent directory ====", path)
Print ( "==== set the path for the test_case files in the current folder parent directory ====", os.path.join (os.path.dirname (os.getcwd ()), "test_case"))



DEF Zidian ( ):
dict = { 'the Name': 'Runoob', 'Age':. 7, 'Class': 'First'}

dict [ 'Age'] = # 88 updates Age
dict [ 'School'] = "Add Information" add information

print ( "dict [ 'Age' ]:", dict [ 'Age'])
Print ( "dict [ 'School']:", dict [ 'School'])




#
# del dict [ 'the Name'] # delete key 'the Name'
# dict.clear () # Empty dictionary
# del dict # delete the dictionary
#
# Print ( "dict [ 'Age']:", dict [ 'Age'])
# Print ( "dict [ 'School']:" immutable refers # called tuple is a tuple memory pointed to by the SUMMARY immutable.
# TUP1 = (12 is, 34.56)
# tup2 = ( 'ABC', 'XYZ')
#
# # the following modifications tuple element operation is illegal.
## TUP1 [0] = 100
#
Create a # # new tuple
# tup3 = TUP1 + tup2
# Print (TUP1)
# Print (tup2)
# Print (tup3)
# Print (tup3 [0]), dict [ 'School'])

#
# About tuples are immutable







# -*- coding:utf-8 -*-
import time as t
import cx_Oracle as oracle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import random,os,math,re,time
class Properties(object):

def __init__(self, fileName):
self.fileName = fileName
self.properties = {}

def __getDict(self,strName,dictName,value):

if(strName.find('.')>0):
k = strName.split('.')[0]
dictName.setdefault(k,{})
return self.__getDict(strName[len(k)+1:],dictName[k],value)
else:
dictName[strName] = value
return
def getProperties(self):
try:
pro_file = open(self.fileName, 'r')
for line in pro_file.readlines():
line = line.strip().replace('\n', '')
if line.find("#")!=-1:
line=line[0:line.find('#')]
if line.find('=') > 0:
strs = line.split('=')
strs[1]= line[len(strs[0])+1:]
self.__getDict(strs[0].strip(),self.properties,strs[1].strip())
except:
raise
else:
pro_file.close()
return self.properties


#
# from PropertiesUtil import Properties
# dictProperties=Properties("global.properties").getProperties()
# print dictProperties
#

def main():
file_path = r'D:\backup\PycharmProjects\charm123\prop.properties'
dictProperties=Properties(file_path).getProperties()
print (dictProperties)
print (type(dictProperties))
print (len(dictProperties))
print (dictProperties['url'])
print (dictProperties['driver'])
hang1=1
try:
hang1=dictProperties['hang1']
except :
hang1=0

print (hang1)


# main()



def zidian():
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

) # # # The following modifications tuple element operation is illegal. # # TUP1 [0] = 100 # # # Create a new tuple # tup3 = TUP1 + tup2 # Print (TUP1) # Print (tup2) # Print (tup3) # Print (tup3 [0]), dict [ ' School ']) # # About tuples are immutable













































First, get the current path

 

      1, using sys.argv [0]

SYS Import 
Print the sys.argv [0] 
# output
# local path

     

      2, os module

Copy the code
os Import 
Print os.getcwd () # Get the current working directory path 
print os.path.abspath ( '.') # get the current working directory path 
print os.path.abspath ( 'test.txt') # get the files in the current directory the working directory path 
print os.path.abspath ( '..') # get the parent directory of the current working! Note that the parent directory path 
print os.path.abspath (os.curdir) # Get the current working directory path
Copy the code

 

 

    3, change the current directory

         1) Use: os.chdir (path).

         For example, if the current directory in the 'E:' below, and then enter the following files E files can be used os.chdir (E: \ files).

         Thereafter, for example, test1 = open ( 'file1.txt'), the file will be opened in the 'E: \ files' directory under the file, rather than the 'E' under.

   

    4, the return path combination

         os.path.join('file1','file2','file3')

         Were combined to obtain path file1 / file2 / file3

>>> print os.path.join('E:', 'file1', 'file2')
E:/file1/file2
>>> print os.path.join('/home', '/home/file1/', '/home/file1/file2/')
/home/file1/file2/

        no.2

Copy the code
os Import 
root = os.getcwd () # get current path / Home / dir1 
Print root 
# output 
# / Home / dir1 

name = "file1" # define the file name of the   
print (os.path.join (root, name) ) # merge path names and file names, and print 
# output 
# / home / dir1 / file1
Copy the code

      

 

Second, access to all files in the current directory

      1. os.walk () in the directory for the file name of the output directory tree walk up or down;

Copy the code
Syntax 
os.walk (top [, topdown = True [, onerror = None [, followlinks = False]]]) 

Parameters: Top - each clip file in the root directory (including itself), to produce 3-tuple ( dirpath, dirnames, filenames) [folder path
folder name, file name]. topdown - Alternatively, or not specified is True, a 3-tuple directory 3- tuple than its subfolders the first generation (directory top-down).
If topdown is False, 3- tuple than generating a directory (directory bottom-up) after the group of 3-membered to its subfolders. onerror - Alternatively, a function; it has a parameter called a OSError example. After reporting this error, continue to walk, or throw an exception terminated walk. followlinks - set to true, then by a soft link to access the directory.
Copy the code

    2.

Copy the code
os Import 
root = os.getcwd () 

DEF file_name (file_dir): 
    for root, dirs, Files in os.walk (file_dir): 
        Print "-----------" 
        Print root # os.walk ( ) directory 
        for all directory names print dirs # os.walk () directory of 
        print files # os.walk all non-directory file name () directory of 
        Print "" 

file_name (root)
Copy the code

  -----------  ---------- ----

 

 

 

Guess you like

Origin www.cnblogs.com/xinxihua/p/12637320.html