1. 程式人生 > >通編碼讀取文件內容

通編碼讀取文件內容

encoding ret os.path () exce turn urn path with open

通編碼讀取文件內容

# 通編碼讀取文件內容
def read_lines_from_file(file_path, coding="utf-8"):
    line_content = []
    if os.path.isfile(file_path):
        try:
            with open(file_path, encoding=coding) as fp:
                line_content = fp.readlines()
            return line_content
        except Exception as e:
            # print(e)
            try:
                with open(file_path, encoding="gbk") as fp:
                    line_content = fp.readlines()
                return line_content
            except Exception as e:
                print(e)
                return []
    elif os.path.isdir(file_path):
        print("%s is a dir! can not read content directly!" % file_path)
        return []
    else:
        print("%s file path does not exist!" % file_path)
        return []

通編碼讀取文件內容