Python讀取寫入獲取文件簡單例子 Python讀取寫入獲取文件簡單例子

Python讀取寫入獲取文件簡單例子

# 對個獲取指定目錄的所有文件
def get_all_files(dir):
    fileList = []
    """遍歷獲取指定文件夾下面所有文件"""
    if os.path.isdir(dir):
        filelist = os.listdir(dir)
        for ret in filelist:
            filename = dir + "\\" + ret
            if os.path.isfile(filename):
                fileList.append(filename)
    return fileList


# 對個獲取指定目錄的所有文件
def get_file_list_by_walk(dir):
    fileList = []
    """使用listdir循環遍歷"""
    if not os.path.isdir(dir):
        return fileList
    dirlist = os.walk(dir)
    for root, dirs, files in dirlist:
        for fi in files:
            fileList.append(os.path.join(root, fi))
    return fileList

#指定文件路徑獲取文件最後文件的路徑包含文件
#如:D:\test\file.txt 返回的結果爲:D:\test\
def get_file_path(path):
    #獲取文件名
    #return os.path.split(path)[1] 
    # 獲取文件路徑
    return os.path.split(path)[0]

#指定文件路徑獲取文件最後文件的路徑包含文件
#如:D:\test\file.txt 返回的結果爲:file.txt
def get_file_name(path):
    return os.path.basename(path)
    
# 創建目錄
def mkdir(path):
    # 去除尾部 \ 符號
    pathx = path.strip().rstrip("\\")
    # 判斷路徑是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(pathx)
    # 判斷結果
    if not isExists:
        # 如果不存在則創建目錄創建目錄操作函數
        os.makedirs(path)
        print(path + ' 創建成功')
        return True
    else:
        # 如果目錄存在則不創建,並提示目錄已存在
        print(path + ' 目錄已存在')
        return False


# 創建一個txt文件,並向文件寫入msg
"""
@file_dir參數 代表文件目錄 如:D:\test
@file_name參數 代表文件名稱 如:file.txt
@msg參數 代表要寫入文件的內容信息
"""
def writer_to_file(file_dir, file_name, msg):
    # 先創建目錄
    mkdir(file_dir)
    # 再打開文件
    full_path = file_dir + "\\" + file_name
    fi = open(full_path, 'w')
    # 寫入文件
    fi.write(msg) 
    fi.close()

"""
通過指定文件路徑文件進行讀取內容
如:D:\test\file.txt
"""
def reader_file(path):
    #解決亂碼問題
    fi = open(path,'r',encoding='gbk',errors = 'ignore')
    strs=[]
    #splitlines解決不換行\n輸出
    for line in fi.read().splitlines():
        if(len(line)>0):
            strs.append(line)
    return strs



   
#測試__main__方法
if __name__ == '__main__':
    path = r"D:\test\test.txt"
    #讀取內容
    fileStr = reader_file(path)
    
    # 最終統計的信息寫入文件
    writer_to_file(path, "file.txt", fileStr)
    
    print('do finish')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章