Python的標準庫中的os模塊包含廣泛的操做系統功能。若是你但願你的程序可以與平臺無關的話,這個模塊是尤其重要的。即它容許一個程序在編寫後不須要任何改動,也不會發生任何問題,就能夠在Linux和Windows下運行。html
下面列出了一些在os模塊中比較有用的部分。它們中的大多數都簡單明瞭。python
os.sep能夠取代操做系統特定的路徑分隔符。windows下爲 「\\」 os.name字符串指示你正在使用的平臺。好比對於Windows,它是'nt',而對於Linux/Unix用戶,它是'posix'。 os.getcwd()函數獲得當前工做目錄,即當前Python腳本工做的目錄路徑。 os.getenv()獲取一個環境變量,若是沒有返回none os.putenv(key, value)設置一個環境變量值 os.listdir(path)返回指定目錄下的全部文件和目錄名。 os.remove(path)函數用來刪除一個文件。 os.system(command)函數用來運行shell命令。 os.linesep字符串給出當前平臺使用的行終止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。 os.path.split(p)函數返回一個路徑的目錄名和文件名。 os.path.isfile()和os.path.isdir()函數分別檢驗給出的路徑是一個文件仍是目錄。 os.path.existe()函數用來檢驗給出的路徑是否真地存在 os.curdir:返回當前目錄('.') os.chdir(dirname):改變工做目錄到dirname os.path.getsize(name):得到文件大小,若是name是目錄返回0L os.path.abspath(name):得到絕對路徑 os.path.normpath(path):規範path字符串形式 os.path.splitext():分離文件名與擴展名 os.path.join(path,name):鏈接目錄與文件名或目錄 os.path.basename(path):返回文件名 os.path.dirname(path):返回文件路徑
第一個python程序(python 3.1.2)shell
建立文件(makeTextFile.py)windows
"這個腳本提醒用戶輸入一個(尚不存在的)文件名,而後由用戶輸入該文件的每一行。最後,將全部文本寫入文件" #!/user/bin/env python 'makeTextFile.py -- create text file' import os ls = os.linesep #get filename filename = input('Enter a file name:') while True: if os.path.exists(filename): print("ERROR: '%s' already exists" % filename) else: break #get file content(text) lines all = [] print("\nEnter lines ('.' by iteself to quit).\n") #loop until user terminates input while True: entry = input('>') if entry == '.': break else: all.append(entry) #write lines to file with proper line-ending fobj = open(filename, 'w') fobj.writelines(['%s%s' %(x, ls) for x in all]) fobj.close() print("Done!")
程序很簡單,相對複雜的就下面這句話app
fobj.writelines(['%s%s' %(x, ls) for x in all])
讀取文件(readTextFile.py)函數
#!/user/bin/env python 'readTextFile.py -- read and display text file' #get file name fname = input('Enter file name:') print() #attempt to open file for reading try: fobj = open(fname, 'r') except IOError as e: print("*** file open error", e) else: #display contents to the screen for eachLine in fobj: print(eachLine, end='') fobj.close()
這個裏面加入了一些異常處理oop
裏面可能比較奇怪的就是我本身修改的這句話了post
print(eachLine, end='')
print裏面加入end=’’這個參數能夠消除print自身添加的換行符,那樣就是能夠保持輸出顯示是和原文件如出一轍了,否則每行就會多個換行符。ui
你還能夠採用這樣的方法來去掉那個換行符spa
print(eachLine.strip())