zoukankan      html  css  js  c++  java
  • python之文件读写操作笔记

    对不同类的文件操作,需要调用相关的库文件,一般情况下,可以选择建立:写文件函数和读文件函数。在写文件与读文件函数中

    我们可以采用:with  open('文件名','w', encoding='utf8') as f:  上下文管理方式来操作文件。
    其中‘w’为打开文件模式,也可以是‘r’,还可以是‘a’

    r  以只读方式打开文件。文件的指针将回放在文件的开头,这是默认模式

    w 打开一个文件只用于写入。如果该文件已存在则覆盖,如果不存在,就创建新文件

    a 打开一个文件用于追加。如果该文件已存在,就从结尾追加。如果没有就新建文件

    接下来就是简单的代码演练了。

     1 def txt_writer():
     2     """写文件"""
     3     with open('data.txt', 'w', encoding='utf8') as f:
     4         f.write('优品课堂
    ')
     5         lines = [
     6             '地址:北京市
    ',
     7             'QQ:95001678
    ',
     8             '网址:http://uke.cc'
     9         ]
    10         f.writelines(lines)
    11 
    12 def txt_read():
    13     """读文件"""
    14     # open中省略'r',也可以
    15     with open('data.txt', encoding='utf8') as f:
    16         # 两种方式读取文件
    17         # for line in f:
    18         #     print(line, end='')
    19         reader = f.readlines()  # 这个与f.writelines对应
    20         print(reader)
    21 
    22 if __name__ == '__main__':
    23     txt_read()
     1 import json  # 调用json库不可少
     2 
     3 def json_basic():
     4     data = {
     5         "ID": 1,
     6         "课程": "Python精讲",
     7         "机构": "优品课堂",
     8         "单价": 98.00,
     9         "网址": "http://codr.cn"
    10     }
    11     print('原始数据')
    12     print(data)
    13     print('_  ' * 20)
    14     json_str = json.dumps(data)
    15     print(json_str)
    16     print('_  ' * 20)
    17     json_data = json.loads(json_str)
    18     print(json_data)
    19 
    20 def json_write_file():
    21     """写json文档"""
    22     data = {
    23         "ID": 1,
    24         "课程": "Python精讲",
    25         "机构": "优品课堂",
    26         "单价": 98.00,
    27         "网址": "http://codr.cn"
    28     }
    29     with open('data.json', 'w', encoding='utf8') as f:
    30         json.dump(data, f)  # 向文件存储数据
    31 
    32 def json_read_file():
    33     """读取json文件"""
    34     with open('data.json', 'r', encoding='utf8') as f:
    35         data = json.load(f)  # 加载文件中的数据
    36         print(data)
    37 
    38 def json_type_diff():
    39     """类型差异"""
    40     # print(json.dumps(False))
    41     data = {
    42         'Discontinued': False,  # 在json下False为false
    43         'Tilte': 'iphone7s',
    44         'category': None,  # 在json下None为none
    45         'Price': 5999.00
    46     }
    47     print(json.dumps(data))
    48 # {"Discontinued": false, "Tilte": "iphone7s", "category": null, "Price": 5999.0}
    49 
    50 
    51 if __name__ == '__main__':
    52     # json_basic()
    53     # json_write_file()
    54     # json_read_file()
    55     json_type_diff()
     1 import xlrd
     2 
     3 def xl_read():
     4     """excel读取"""
     5     book = xlrd.open_workbook('product.xlsx')
     6     for sheet in book.sheets():  # 读取Excel表里的工作簿在表的下方sheet里
     7         print(sheet.name)        # 这里sheet的别名不能出现空格
     8 
     9 def xl_read_data():
    10     """读取数据"""
    11     # 用xlrd.open_workbook('文件名.xlxs')方式打开Excel文件
    12     book = xlrd.open_workbook('product.xlsx')
    13     sheet = book.sheet_by_name("product")
    14     print('工作簿:{}'.format(sheet.name))
    15     print('数据行数:{}'.format(sheet.nrows))
    16     print("产品数据")
    17     print("=" * 50)
    18     for i in range(sheet.nrows):
    19         print(sheet.row_values(i))  # 获取索引指定的数据行
    20 
    21 if __name__ == '__main__':
    22     # xl_read()
    23     xl_read_data()
     1 import csv  # 调用csv库是不可少的
     2 """先运行csv_write部分即写入csv文件"""
     3 
     4 """这是csv文件的基本操作"""
     5 
     6 def csv_reader():
     7     """读取csv"""
     8 
     9     with open('my_course2.csv', encoding='utf8') as f:
    10         reader = csv.reader(f)  # 以列表的方式读取赋值给reader
    11         # reader = csv.DictReader(f)  # 以顺序字典表的方式读取赋值给reader
    12         headers = next(reader)  # 用next迭代方式打印
    13         print(headers)
    14         for row in reader:
    15             print(row)
    16 
    17 def csv_write():
    18     """写入csv文件"""
    19     """"先创建写的内容"""
    20     headers = ["编号", "课程", "讲师"]
    21     # 不能忘记每一行后面的“,”
    22     rows = [
    23         (1, "Python", "Eason"),
    24         (2, "c#", "Eason"),
    25         (3, "Django", "Eason"),
    26         (4, ".NET", "Eason")
    27     ]
    28     """newline=''是为了写入文件的每一行不要有空行"""
    29     with open('my_course.csv', 'w', encoding='utf8', newline='') as f:
    30         writer = csv.writer(f)
    31         writer.writerow(headers)  # 写入标头
    32         writer.writerows(rows)   # 写入标头以下行writerows比上一行多个s
    33 
    34 def csv_writer_dict():
    35     """以dict形式写入csv"""
    36     """"先创建写的内容"""
    37     headers = ["ID", "Title", "org", "Url"]
    38     # 不能忘记每一行后面的“,”
    39     rows = [
    40         {'ID': 1, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
    41         {'ID': 2, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
    42         {'ID': 3, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
    43         {'ID': 4, 'Title': 'Python', 'org': 'youpinketang', 'Url': 'http://uke.cc'},
    44         dict(ID=5, Title='C#', org='youpinketang', Url='http://codr.cn'),
    45         dict(ID=6, Title='C#', org='youpinketang', Url='http://codr.cn')
    46     ]
    47     """通过with... as ...形式方便程序进程管理"""
    48     with open('my_course2.csv', 'w', encoding='utf8', newline='') as f:
    49         writer = csv.DictWriter(f, headers)  # 以字典表的形式写入文件
    50         writer.writeheader()  # 写入第一行标头
    51         writer.writerows(rows)  # 写入标头行以下行
    52 
    53 if __name__ == '__main__':
    54     # csv_write()
    55     csv_reader()
    56     # csv_writer_dict()
  • 相关阅读:
    实验 7:OpenDaylight 实验——Python 中的 REST API 调用
    实验 6:OpenDaylight 实验——OpenDaylight 及 Postman实现流表下发
    实验 5:OpenFlow 协议分析和 OpenDaylight 安装
    实验 4:Open vSwitch 实验——Mininet 中使用 OVS 命令
    实验 3:Mininet 实验——测量路径的损耗率
    软件工程第一次作业——自我介绍
    实验 2:Mininet 实验——拓扑的命令脚本生成
    实验1、Mininet 源码安装和可视化拓扑工具
    第01组 Beta版本演示
    第01组 Beta冲刺(4/4)
  • 原文地址:https://www.cnblogs.com/yang901112/p/11349626.html
Copyright © 2011-2022 走看看