·读
1 2 3 4 | file = open("sample.txt") for line in file: pass # do something file.close() |
去除换行符
1 2 3 | for line in file.readlines(): line=line.strip(' ') pass # do something |
·写:
1 2 3 4 | line= "aaaaaaaaadddd" file = r'/root/l0626/test.txt' with open(file, 'a+') as f: f.write(line+' ') |
·关于参数
'r':读 'w':写 'a':追加 'r+' == r+w(可读可写,文件若不存在就报错(IOError)) 'w+' == w+r(可读可写,文件若不存在就创建) 'a+' ==a+r(可追加可写,文件若不存在就创建) 对应的,如果是二进制文件,就都加一个b就好啦: 'rb' 'wb' 'ab' 'rb+' 'wb+' 'ab+' |