學弟教程·Python文件操作

一、實驗目的

掌握Python文件操作

二、實驗環境

  • 系統環境 : Windows 10 2004
  • IDE : Pycharm
  • Python: Python 3.8

三、文件操作

文件路徑問題

Windows中因爲 " \ "被當成了轉義字符,會導致路徑找不到
例如 : C:\Users\xxx\Desktop\x.txt需改寫爲以下三種形式之一

  • r’C:\Users\xxx\Desktop\x.txt’

  • ‘C:\Users\xxx\Desktop\x.txt’

  • ‘C:/Users/xxx/Desktop/x.txt’

3.1 創建文件

3.1.1 當前項目路徑

import os

def create_file(file_name):
    # 獲取當前路徑
    path = os.getcwd()
    # 獲得文件的路徑
    file_path = os.path.join(path,file_name)
    # 如果該文件存在
    if os.path.exists(file_path):
        print('該文件已經存在')
        return
    # 創建文件
    f = open(file_path,'w',encoding='utf-8')
    if os.path.exists(file_path):
        f.close()
        print('%s 文件創建成功'%file_name)
        return
    print('%s 文件創建失敗' % file_name)

3.1.2 指定路徑

僅需將3.1.1中的path變量的值換爲指定的路徑值即可,需注意文件路徑的問題

3.2 修改文件

3.2.1 寫入內容

def write_file(file_name):
    path = os.getcwd()
    # 獲得文件的路徑
    file_path = os.path.join(path, file_name)
    with open(file_path, 'w',encoding='utf-8') as f:
        data = input('輸入內容:')
        f.write(data)
    f.close()

3.2.2 追加內容

def add_file_data(file_name):
    path = os.getcwd()
    file_path = os.path.join(path, file_name)
    with open(file_path, 'a', encoding='utf-8') as f:
        data = input('輸入追加的內容:')
        f.write('%s\n'%data)
    f.close()
  • with open中的參數a代表追加內容
  • '\n’實現換行

3.2.3 覆蓋內容

與3.2.1寫入文件內容的代碼一致

3.2.4 重命名

def rename_file(old_name,new_name):
    path = os.getcwd()
    old_path = os.path.join(path, old_name)
    new_path = os.path.join(path, new_name)
    os.rename(old_path, new_path)

3.3 讀取文件

3.3.1 整體讀取

def read_file(file_name):
    path = os.getcwd()
    # 獲得文件的路徑
    file_path = os.path.join(path, file_name)
    with open(file_path, 'r', encoding='utf-8') as f:
        data = f.read()
        print(data)
    f.close()

3.3.2 逐行讀取

修改3.3.1代碼爲

with open(file_path, 'r', encoding='utf-8') as f:
    data = f.readlines()
    for i in data:
        print(i)

3.4 移動/複製文件

移動文件

import os
import shutil

def move_file(source_path, target_path):
    if not os.path.isfile(source_path):
        print('待移動文件不存在')
        return
    file_path, file_name = os.path.split(target_path)
    if not os.path.exists(file_path):
        os.makedirs(file_path)
    shutil.move(source_path, target_path)
    print('移動成功')

if __name__ == '__main__':
    source_path = 'D:/Code/Python/File/newFiles.txt'
    target_path = 'D:/Move/file.txt'
    move_file(source_path, target_path)

複製文件
將shutil.move()換爲shutil.copyfile()即可

shutil.copyfile(source_path, target_path)

3.5 刪除文件

def delete_file(source_path):
    if  not os.path.exists(source_path):
        print('待刪除文件不存在')
        return
    os.remove(source_path)

四、文件夾操作

4.1 讀取

4.1.1 顯示文件夾中文件

def display_all_files(folder_path):
    for i in os.listdir(folder_path):
        path = os.path.join(folder_path, i)
        # 如果是文件
        if os.path.isfile(path):
            print(path)

4.1.2 遞歸顯示文件夾中文件

def display_all_folders(folder_path):
    for i in os.listdir(folder_path):
        path = os.path.join(folder_path, i)
        # 如果該對象是文件夾
        if os.path.isdir(path):
            print("--folder : %s"%i)
            display_all_files(path)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章