os模組常用函式

2021-09-24 18:40:33 字數 1568 閱讀 1223

#同樣,執行後重新開啟檔案檢視變化

import os

'''with open ('c:\\users\\administrator\\desktop\\text\\kk.txt','r') as f:

lines = f.readlines()

with open('c:\\users\\administrator\\desktop\\text\\test_new.txt','w') as new: # 新建乙個文件

for line in lines:

print(line)

if line not in ['0\n','1\n']:

new.write(line)

'''# 可以先執行一次**,然後,再將下面**的注釋取消,再執行一次。

#os.replace('c:\\users\\administrator\\desktop\\text\\test_new.txt', 'c:\\users\\administrator\\desktop\\text\\test1.txt') # 語法:os.replace(file1,file2),將file1重新命名為file2,將其替代。

# 請你根據上面的方法,將之前的**改為用模組 os 實現(可選文件poem2)。

# 在改**之前,可以先將上面的**注釋,然後取消下面**的注釋。

list_test = ['一弦一柱思華年。\n','只是當時已惘然。\n']

with open ('c:\\users\\administrator\\desktop\\text\\test_new.txt','r') as f:

lines = f.readlines()

with open('c:\\users\\administrator\\desktop\\text\\poem2.txt','w') as new:

for line in lines:

if line in list_test:

new.write('____________。\n')

else:

new.write(line)

a=os.getcwd()#os.getcwd()返回當前工作目錄

print(a)

b=os.listdir('c:\\users\\administrator\\desktop\\text') # 返回path指定的資料夾包含的檔案或資料夾的名字的列表

print(b)

#os.mkdir('c:\\users\\administrator\\desktop\\text\\book') # 建立資料夾

c=os.path.abspath('kk.txt') # 返回絕對路徑os.path.abspath(path)

print(c)

d=os.path.basename('c:\\users\\administrator\\desktop\\text\\poem2.txt') # 返回檔名

print(d)

#os.path.isfile(path) # 判斷路徑是否為檔案

#os.path.isdir(path) # 判斷路徑是否為目錄

os模組常用函式

os.sep 系統的路徑分隔符 os.name 制定系統工作平台,比如對於windows,它是 nt 而對於linux unix使用者,它是 posix os.getcwd 當前工作目錄 os.curdir 返回前目錄 os.listdir directory 返回指定目錄下的所有檔案的目錄名 os...

OS模組常用函式講解

os 模組是 python 標準庫中的乙個用於訪問作業系統的模組,包含普遍的作業系統功能,如複製 建立 修改 刪除檔案及資料夾。os 模組提供了乙個可移植的方法來使用作業系統的功能,使得程式能夠跨平台使用,即它允許乙個程式在編寫後不需要任何改動,就可以在 linux 和 windows 等作業系統下...

常用模組 os模組

主要用於與計算機系統互動 print os.getcwd 獲取當前工作目錄 f python exe day20 os.chdir f python exe day20 pack 更改當前工作目錄 print os.getcwd f python exe day20 pack print os.cu...