Python之讀寫文件梳理

                                                    Python之讀寫文件梳理

       實際應用中,經常需要進行讀寫文件等IO操作,Python內置相應讀寫函數。下面主要總結了常用讀寫文件操作函數及.ini、csv、excel三種類型文件的讀寫。

一、常用讀寫函數

1、open():打開文件、read():讀、write():寫

io.open() : 打開文件,從而對文件進行讀 f.read()、寫 f.write()操作 

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
   pass

open()函數mode主要有以下幾種,標示符’r+’表示可讀寫2種方式, ‘a’以追加的方式寫入,不會清空文件原來的內容。

========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists
'b'       binary mode
't'       text mode (default)
'+'       open a disk file for updating (reading and writing)
'U'       universal newline mode (deprecated)
========= ===============================================================

2、例子

def load_file(file_path):
    with io.open(file_path, "r+", encoding="utf-8-sig") as f:
        try:
            content_json = json.loads(f.read())       ## 文件內容{"code": "1", "name": "名稱1"} json類型,讀取 f.read()
            print(content_json["code"])               # 獲取值
            f.write('{"code": "2", "name": "名稱2"}')  # 寫入f.write
        except (KeyError, TypeError):
            sys.exit(1)

 

二、.ini、csv、excel 文件讀寫梳理

1、.ini : ConfigParser模塊

      ConfigParser : 常用的操作ini文件模塊,但無法識別section的大小寫,無法讀取文件註釋。

文件內容:

[user]
username = zz
password = abc123
通過調用如下函數獲取username,load_file("test.ini", "user", "username")
def load_file(file_path, section, item):
    cf = configparser.ConfigParser()
    cf.read(file_path, encoding='utf-8')
    test_value = cf.get(section, item)
    print(test_value)       ## print 結果:zz

    # add
    cf.add_section("add")
    cf.set("add", "test_param", "test_value")
    cf.write(open(file_path, "w"))

文件內容如下:

 

2、csv: csv、pandas

這裏主要介紹通過csv讀寫的方式。

具體實現如下:

def read_file(file):
    with open(file, encoding='UTF-8') as csv_file:
        result = []
        for row in csv.DictReader(csv_file):
            result.append(row)           # 讀取文件內容到result中
            print(row.get('username'))   # 獲取username  

def write_file(file):
    with open(file, 'a', encoding='UTF-8') as f:     # mode:a  追加寫入方式
        csv_file = csv.writer(f)
        csv_file.writerow(['username', 'password'])
        csv_file.writerow(['大白1', 'abc123'])
        csv_file.writerow(['大白2', 'abc123’])

通過 write_file("test.csv")  read_file("test.csv") 調用,文件內容如下:

 

3、Excel: xlrd(讀取)

Python中也提供不同的依賴包實現對Excel文件的讀寫,這裏主要梳理xlrd讀取Excel 的方式。

返回Excel中的內容 dataresult 進行不同操作。

def get_xls_data(xlsfile, sheetnum):
    dataresult = {}
    excel_file = xlrd.open_workbook(xlsfile)
    sheet = excel_file.sheet_by_index(sheetnum)
    tab = sheet.row_values(0)
    for i in range(1, sheet.nrows):
        row_content = sheet.row_values(i, 0, sheet.ncols)
        temp = dict(zip(tab, row_content))
        dataresult[i] = temp
    return dataresult

實際應用中,根據需要進行不同的改動。

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