文件的处理

一、文件路径

  1. 绝对路径:
FILE = r'C:\Temp\iris.csv'
FILE = r'/tmp/iris.csv'
  1. 相对路径:
FILE = r'iris.csv'
FILE = r'../data/iris.csv'

二、读取文件

  1. 逐行读文件
with open(r'/tmp/iris.csv') as file:
for line in file:
print(line)

eg:
FILE = r'D:\ai\homework2\txtdata\dd.json' 
with open(FILE) as file:
    for line in file:
        print(line)
#打印结果:
dd = {'a': 'ok1', '1': {'1': 11, '2': ('a', 111, {'a': 'ok2'}, [{'a': 'ok3'}, 2222], {'a': [11111, 22222]})}, '2': '2'}  
  1. 阅读整个文件内容
with open(r'/tmp/iris.csv') as file:
content = file.read()

#eg:
with open(r'D:\ai\homework2\txtdata\dd.json') as file:
    content = file.read()
    print(content)
#打印结果:
dd = {'a': 'ok1', '1': {'1': 11, '2': ('a', 111, {'a': 'ok2'}, [{'a': 'ok3'}, 2222], {'a': [11111, 22222]})}, '2': '2'}  
  1. 读取文件作为一行列表
with open(r'/tmp/iris.csv') as file:
lines = file.readlines()

eg:
with open(r'D:\ai\homework2\txtdata\dd.json') as file:
    lines = file.readlines()
    print(lines)
#打印结果:
["dd = {'a': 'ok1', '1': {'1': 11, '2': ('a', 111, {'a': 'ok2'}, [{'a': 'ok3'}, 2222], {'a': [11111, 22222]})}, '2': '2'}  "]
  1. 读文件选取特定的行
with open(r'/tmp/iris.csv') as file:
lines = file.readlines()[1:30]

eg:
with open(r'D:\ai\homework2\txtdata\number.json') as file:
    lines = file.readlines()[0:30]
    print(lines)
#打印结果:
#['{\n', '    "MaskPolygonItem": {\n', '        "0": {\n', '            "BoundingBox": "354.105 221.957 379.764 96.2241",\n', '            "label": "Number",\n', '            "labelNum": 0,\n', '            "polygon": "3,6"\n', '        }\n', '    },\n', '    "channels": 3,\n', '    "height": 1080,\n', '    "width": 1920\n', '}']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值