一、文件路径
- 绝对路径:
FILE = r'C:\Temp\iris.csv'
FILE = r'/tmp/iris.csv'
- 相对路径:
FILE = r'iris.csv'
FILE = r'../data/iris.csv'
二、读取文件
- 逐行读文件
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'}
- 阅读整个文件内容
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'}
- 读取文件作为一行列表
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'} "]
- 读文件选取特定的行
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', '}']