- # 通编码读取文件内容
- 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 []
来源: http://www.bubuko.com/infodetail-2997444.html