Pandas excelwriter tạo tệp nếu không tồn tại

Bài viết này sẽ cho bạn biết một số phương pháp về cách sử dụng mô-đun python

$ pip install xlwt
$ pip install openpyxl
8 và
$ pip install xlwt
$ pip install openpyxl
9 để vận hành các tệp. Các nhiệm vụ được liệt kê dưới đây

  1. Kiểm tra xem tệp có tồn tại hay không, tạo tệp nếu không tồn tại
  2. Kiểm tra xem tệp là thư mục hay tệp
  3. Kiểm tra xem tệp có thể đọc, ghi hoặc thực thi được không
  4. Cách tạo một tệp mới
  5. Cách tạo thư mục mới
  6. Cách thay đổi quyền truy cập tệp

1. Kiểm tra sự tồn tại của tệp/thư mục

Có ba phương pháp có thể kiểm tra sự tồn tại của tệp hoặc thư mục

  1. Sử dụng phương pháp
    $ pip install xlwt
    $ pip install openpyxl
    0
  2. Bắt đối tượng
    $ pip install xlwt
    $ pip install openpyxl
    1
  3. Sử dụng mô-đun
    $ pip install xlwt
    $ pip install openpyxl
    9. Mô-đun này là mô-đun tích hợp sẵn trong Python3 nhưng nếu bạn sử dụng Python2 thì cần cài đặt riêng

2. Kiểm tra xem đường dẫn là thư mục hay tệp

  1. Sử dụng phương pháp
    $ pip install xlwt
    $ pip install openpyxl
    3
  2. Sử dụng phương pháp
    $ pip install xlwt
    $ pip install openpyxl
    4 hoặc
    $ pip install xlwt
    $ pip install openpyxl
    5

3. Kiểm tra trạng thái có thể đọc, có thể ghi hoặc có thể thực thi của tệp

  1. Sử dụng phương pháp
    $ pip install xlwt
    $ pip install openpyxl
    6

4. Tạo tệp mới

  1. Mở một đối tượng tệp
  2. Gọi phương thức
    $ pip install xlwt
    $ pip install openpyxl
    80 của đối tượng tập tin

5. Tạo thư mục mới

  1. Sử dụng phương pháp
    $ pip install xlwt
    $ pip install openpyxl
    81

6. Thay đổi quyền đối với tệp

  1. Sử dụng phương pháp
    $ pip install xlwt
    $ pip install openpyxl
    82

7. Ví dụ mã

Dưới đây là mã nguồn ví dụ

import os, stat
import pathlib

# Check file/folder existence by os.path.exists method.
def checkFileExistByOSPath[file_path]:

    ret = False
    # If this file object exist.
    if[os.path.exists[file_path]]:
        ret = True
        print[file_path + " exist."]
        # If this is a file.
        if[os.path.isfile[file_path]]:
            print[" and it is a file."]
        # This is a directory.    
        else:
            print[" and it is a directory."]
    else:
        ret = False
        print[file_path + " do not exist."]
        
    return ret

# Check file/folder existence by exception.         
def checkFileExistByException[file_path]:
    ret = True
    try:
        # Open file object.
        file_object = open[file_path, 'r']
        # Read entire file content data.
        file_data = file_object.read[]
        print[file_path + " exist. It's data : " + file_data]
    except FileNotFoundError:
        ret = False
        print[file_path + " do not exist."]
    except IOError:
        ret = False
        print[file_path + " can not be read. "]    
    except PermissionError:
        ret = False
        print["Do not have permission to read file " + file_path]

    return ret

# Check file/folder existence by pathlib.         
def checkFileExistByPathlib[file_path]:
    ret = True
        
    # Create path lib object.
    pl = pathlib.Path[file_path]
    
    # Check whether the path lib exist or not.
    ret = pl.exists[]
    
    if[ret]:
        print[file_path + " exist."]
    else:
        print[file_path + " do not exist."]
    
    if[pl.is_file[]]:
        print[file_path + " is a file."]
       
    if[pl.is_dir[]]:
        print[file_path + " is a directory."]
    
    return ret

# Check file/folder status by os.access method.
def checkFileStatusByOSAccess[file_path]:
    # If this file exist.
    if[os.access[file_path, os.F_OK]]:
        print[file_path + " exist."]
    else:
        print[file_path + " do not exist."]
            
    if[os.access[file_path, os.R_OK]]:
        print[file_path + " is readable."]
        
    if[os.access[file_path, os.W_OK]]:
        print[file_path + " is writable."]    
        
    if[os.access[file_path, os.EX_OK]]:
        print[file_path + " is executable."]

# Create a new file and write some text in it.
def createNewFile[file_path]:
    file_object = open[file_path, 'w']
    file_object.write['File is created.']
    print[file_path + " has been created. "]
    
# Create a new directory.
def createNewFolder[file_path]:
    if[not checkFileExistByOSPath[file_path]]:
        os.mkdir[file_path]
        print[file_path + " has been created. "]

# Change the file permission to read and execute only.
def setFilePermission[file_path]:
    os.chmod[file_path, stat.S_IEXEC | stat.S_IREAD]
     
        
if __name__ == '__main__':
    file_folder = "./test"
    createNewFolder[file_folder]
    
    file_path = file_folder + "/abc.txt"
    # Check file existence.
    # fileExist = checkFileExistByException[file_path]
    # fileExist = checkFileExistByOSPath[file_path]
    fileExist = checkFileExistByPathlib[file_path]
    # If file do not exist then create it.
    if[not fileExist]:
        createNewFile[file_path]
        setFilePermission[file_path]

    checkFileStatusByOSAccess[file_path]

Viết Excel với Python Pandas. Bạn có thể ghi bất kỳ dữ liệu nào [danh sách, chuỗi, số, v.v.] vào Excel, trước tiên bằng cách chuyển đổi dữ liệu đó thành Khung dữ liệu Pandas và sau đó ghi Khung dữ liệu vào Excel

Để xuất Khung dữ liệu Pandas dưới dạng tệp Excel [phần mở rộng. . xlsx,. xls], sử dụng phương pháp

$ pip install xlwt
$ pip install openpyxl
4

khóa học liên quan. Phân tích dữ liệu với Python Pandas

cài đặtxlwt, openpyxl

$ pip install xlwt
$ pip install openpyxl
4 sử dụng thư viện có tên là xlwt và openpyxl trong nội bộ

  • xlwt được sử dụng để viết. xls [định dạng lên đến Excel2003]
  • openpyxl được sử dụng để viết. xlsx [định dạng Excel2007 trở lên]

Cả hai có thể được cài đặt với pip. [pip3 tùy thuộc vào môi trường]

1
2
$ pip install xlwt
$ pip install openpyxl

Viết Excel

Ghi DataFrame vào tệp Excel

Cần nhập openpyxl nếu bạn muốn nối nó vào tệp Excel hiện có được mô tả ở cuối.
Một khung dữ liệu được xác định bên dưới.

1
2
3
4
5
6
7
8
9
10
11
import pandas as pd
import openpyxl

df = pd.DataFrame[[[11, 21, 31], [12, 22, 32], [31, 32, 33]],
index=['one', 'two', 'three'], columns=['a', 'b', 'c']]

print[df]
# a b c
# one 11 21 31
# two 12 22 32
# three 31 32 33

Bạn có thể chỉ định một đường dẫn làm đối số đầu tiên của

$ pip install xlwt
$ pip install openpyxl
6

Ghi chú. rằng dữ liệu trong tệp gốc sẽ bị xóa khi ghi đè lên

Đối số

$ pip install xlwt
$ pip install openpyxl
7 là tên của sheet. Nếu bỏ qua, nó sẽ được đặt tên là
$ pip install xlwt
$ pip install openpyxl
8

$ pip install xlwt
$ pip install openpyxl
0
$ pip install xlwt
$ pip install openpyxl
1

khóa học liên quan. Phân tích dữ liệu với Python Pandas

Nếu không cần ghi chỉ số [tên hàng], cột [tên cột] thì đối số chỉ số, cột là Sai

$ pip install xlwt
$ pip install openpyxl
0
$ pip install xlwt
$ pip install openpyxl
3

Viết nhiều DataFrames vào tệp Excel

Đối tượng ExcelWriter cho phép bạn sử dụng nhiều gấu trúc. Các đối tượng DataFrame có thể được xuất sang các trang riêng biệt

Như một ví dụ, gấu trúc. Chuẩn bị một đối tượng DataFrame khác

$ pip install xlwt
$ pip install openpyxl
4
$ pip install xlwt
$ pip install openpyxl
5

Sau đó sử dụng hàm ExcelWriter[] như thế này

$ pip install xlwt
$ pip install openpyxl
0
$ pip install xlwt
$ pip install openpyxl
1

Bạn không cần phải gọi cho nhà văn. lưu [], nhà văn. close[] trong các khối

Nối vào một tệp Excel hiện có

Bạn có thể nối thêm DataFrame vào tệp Excel hiện có. Đoạn mã dưới đây mở một tệp hiện có, sau đó thêm hai trang tính với dữ liệu của các khung dữ liệu

Chủ Đề