Python implements reading and writing of txt, excel, csv files [with source code]

Table of contents

foreword

1. Read and write txt files

2. Excel file reading and writing

Summarize


foreword

This article introduces the use of Python to read and write files, including txt files, excel files (xlsx, xls, csv)

The compiler is using PyCharm


1. Read and write txt files

  • read()                  # read all content at once
  • readline()            # read the first line
  • readlines()          # Read all the content of the text and return it in the format of an array
  • write()                # write file content

txt file read and write rules

  • r : read the file, if the file does not exist, an error will be reported
  • w : write to the file, if the file does not exist, it will be created first and then written, and the original file will be overwritten
  • a : write to the file, if the file does not exist, it will be created first and then written, but the original file will not be overwritten, but will be appended at the end of the file
  • rb,wb : similar to r,w respectively, but for reading and writing binary files
  • r+ : readable and writable, an error will be reported if the file does not exist, and it will be overwritten when the file is written
  • w+ : readable, writable, if the file does not exist, create it first, and it will be overwritten
  • a+ : readable and writable, if the file does not exist, it will be created first, it will not be overwritten, and it will be appended at the end 
def readTxt(str):
    with open(str, "r", encoding="utf-8") as f:
        # data = f.read() # 一次性读取全部内容
        # data = f.readline() # 读取第一行内容
        # data = f.readlines() # 读取文本全部内容,并以数列的格式返回
        # print(data)
        for line in f.readlines():
            line = line.strip('\n') # 去掉readlines里的换行符'\n'
            print(line)


def writeTxt(str):
    with open(str, "w", encoding="utf-8") as f:
        f.write("这是个测试!") # 自带文件关闭功能,不需要再写f.close()


if __name__ == '__main__':
    str = "test.txt"
    # readTxt(str) # 读txt文件
    writeTxt(str) # 写txt文件

2. Excel file reading and writing

  • To read excel files, you need to install the xlrd module. The xlrd module of the higher version does not support the reading of xlsx files. You can specify to download the lower version, or save the xlsx file as an xls file
  • Writing excel files requires installing the xlsxwriter module
  • Briefly explain adding TODO before the comment : it means the task to be done, and generally indicates the task person, task time, contact information of the task person and other information. It can be viewed uniformly under the PyCharm editor

excel file read

  • xx = xlrd.open_workbook(r"test.xls"): open excel file
  • xs = xx.sheet_by_name('Sheet1'): read a single table named Sheet1
  • xs = xx['Sheet1']: equivalent to xx.sheet_by_name('Sheet1')
  • xss = xx.sheet_names(): Read all the sheets in the excel file

excel file write

  • workbook = xlsxwriter.Workbook('test.xlsx'): Create a new excel file named test
  • worksheet = workbook.add_worksheet('sheet'): Create a new table named sheet
  • worksheet.write('A1','100'): write 100 in A1, only single write
  • worksheet.write_row('A1',a): Write list a row by row, multiple write
  • worksheet.write_column('A1',b): Write list b one by one, multiple writes
  • wrokbook.close(): close and save the file
import xlrd #TODO 导入xlrd库,使用xlrd中open_workbook和sheet_by_name方法
import xlsxwriter #TODO 导入xlsxwriter库,使用xlsxwriter中Workbook和add_worksheet方法

def readExcel():
    # TODO 定义一个列表A待会储存读取的信息
    A = []
    xx = xlrd.open_workbook(r"test.xls")  # 高版本xlrd不支持xlsx,支持xls
    # xs = xx.sheet_by_name('Sheet1')
    # xs = xx['Sheet1']  # 读单个sheet
    xss = xx.sheet_names()  # 读全部sheet
    for names in range(len(xss)):
        name = xx[xss[names]]
        if xss[names] == 'Sheet1' or xss[names] == 'sheet1':  # sheet子表名称兼容
            print(name)
            xs = name

    for i in range(0, 6):
        k = xs.row_values(i)  # row_values():行值
        print(k)
        A.append(k)
    print(list(A))
    # print(xs.row_values(0)) # row_values():行值
    # N = xs.col_values(1) # col_values():列值
    # print(N)
    # # 这里我们查看一下G的格式是列表还是元组,或者其他的
    # print(type(N))


def writeExcel():
    # datas = (
    #     ['rent', 1000],
    #     ['gas', 120],
    #     ['food', 300],
    #     ['gym', 50],
    #     ['app', 600],
    #     ['lemon', 5000]
    # )
    # workbook = xlsxwriter.Workbook('excel01.xlsx') # csv、xls、xlsx格式都可 对文件操作
    # worksheet = workbook.add_worksheet() # 对文件中的sheet操作
    # row, col = 0, 0
    # for item, cost in datas:
    #     worksheet.write(row, col, item)
    #     worksheet.write(row, col+1, cost)
    #     row += 1
    # worksheet.write(row, 0, 'total')
    # worksheet.write(row, 1, '=sum(B1:B6)')
    # workbook.close()
    head = ['姓名', '分数']
    name = ['张三', '李四', '王五', '老六']
    mark = [66, 77, 88, 99]
    workbook = xlsxwriter.Workbook('chengji.xlsx')
    worksheet = workbook.add_worksheet('chengji')  # 可写指定sheet名
    worksheet.write_row('A1', head)  # write_row():行操作 多个写入
    worksheet.write_column('A2', name)  # write_column():列操作 多个写入
    worksheet.write_column('B2', mark)
    worksheet.write('A6', 'total')  # 单个写入
    worksheet.write('B6', '=sum(B2:B5)')
    workbook.close()


if __name__ == '__main__':
    print("Hello PyCharm!")
    readExcel()  # 读excel
    # writeExcel()  # 写excel


Summarize

This article implements Python's file read and write operations, including txt files, xlsx, xls, csv and other files. Secondly, the method of reading and writing the file is also indicated. This is often encountered in practical applications. If you find it useful, remember to pay attention to favorites, likes and encouragement! ! !

Guess you like

Origin blog.csdn.net/Gary_ghw/article/details/130410075